Reputation: 436
I have a bunch of models setup in Doctrine, where some of the models are in different databases. Doctrine's schema generation tool seems to be generating inter-database foreign keys, but not cross-database foreign keys.
For example:
/**
* @ORM\Entity
* @ORM\Table(name="db1.Contact")
**/
class Contact {
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue
**/
private $id;
}
/**
* @ORM\Entity
* @ORM\Table(name="db2.Subscription")
**/
class Subscription {
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue
**/
private $id;
/**
* @ORM\ManyToOne(targetEntity="Contact")
* @ORM\JoinColumn(name="contact_id", referencedColumnName="id")
*/
private $contact;
}
Critically, hydrating these entities works totally fine, but the schema tool simply doesn't generate the foreign keys.
Has anyone ran into this before? There is another SO post however it is unfortunately unanswered.
Upvotes: 5
Views: 1507
Reputation: 436
Doctrine does not support cross-database foreign keys, however it can be modified to do so. The library seems to take a "not everyone can support it, so no one should" approach. This instance works for MySQL.
When generating a schema, a pre-step is ran using the RemoveNamespacedAssets
visitor. This removes all references to any classes outside of what you are generating.
In the acceptForeignKey
function of that class, comment the following code:
// The table may already be deleted in a previous
// RemoveNamespacedAssets#acceptTable call. Removing Foreign keys that
// point to nowhere.
if ( ! $this->schema->hasTable($fkConstraint->getForeignTableName())) {
$localTable->removeForeignKey($fkConstraint->getName());
return;
}
Running a schema creation or update will now create foreign keys as expected. It is possible this will have other unintended side effects but I haven't ran into any yet.
Upvotes: 8