entityManager->getConnection()->createSchemaManager()->introspectSchema(); $items = $this->concatPrefix('initiative_allocation_items'); if (!$schema->hasTable($items)) { $this->addSql($this->getCreateTableSql()); } if (!$this->hasPlanForeignKey($schema)) { $this->addSql($this->generateAlterTableForeignKeyStatement( 'initiative_allocation_items', ['plan_id'], 'initiatives', ['id'], 'ON DELETE CASCADE' )); } } private function hasPlanForeignKey(Schema $schema): bool { $items = $this->concatPrefix('initiative_allocation_items'); if (!$schema->hasTable($items)) { return false; } foreach ($schema->getTable($items)->getForeignKeys() as $foreignKey) { if (in_array('plan_id', $foreignKey->getLocalColumns(), true)) { return true; } } return false; } private function getCreateTableSql(): string { $schemaTool = new SchemaTool($this->entityManager); $prefix = 'CREATE TABLE '.$this->concatPrefix('initiative_allocation_items').' '; foreach ($schemaTool->getCreateSchemaSql([$this->entityManager->getClassMetadata(InitiativeAllocationItem::class)]) as $sql) { if (str_starts_with($sql, $prefix)) { return $sql; } } throw new \RuntimeException('SchemaTool returned no CREATE TABLE statement for initiative_allocation_items.'); } }