Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine doesn't generate cross-database foreign keys

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.

like image 954
Knifa Avatar asked May 12 '15 14:05

Knifa


1 Answers

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.

like image 133
Knifa Avatar answered Oct 31 '22 20:10

Knifa