Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine ManyToOne w/o a primary ID key

I'm trying to setup an FK between 2 entities in my DB. The parent table has a ManyToOne relationship to a child table. I can not join these tables using a normal parent_id => id FK due to how the child table is populated by external processes (the parent never knows the primary ID of the child).

Doctrine accepts the entities as shown below but Mysql fails when trying to add the FK to the table with the following error.

ALTER TABLE parent_tbl ADD CONSTRAINT FK_1172A832F85E0677 FOREIGN KEY (username) REFERENCES child_tbl (username);

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`dmname`.`#sql-f16_d8acf`, CONSTRAINT `FK_1172A832F85E0677` FOREIGN KEY (`username`) REFERENCES `child_tbl` (`username`))

class Parent
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;


    /**
     * @ORM\ManyToOne(targetEntity="Child")
     * @ORM\JoinColumn(name="username", referencedColumnName="username", nullable=false)
     */
    protected $username;

    // ...
}

class Child
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     *
     * @var integer
     */
    protected $id;

    /**
     * @ORM\Column(type="string", unique=true)
     *
     * @var string
     */
    protected $username;

    // ....
}
like image 788
lifo Avatar asked Sep 26 '22 04:09

lifo


1 Answers

From the Doctrine limitations and known issues :

It is not possible to use join columns pointing to non-primary keys.
Doctrine will think these are the primary keys and create lazy-loading proxies with the data, which can lead to unexpected results.
Doctrine can for performance reasons not validate the correctness of this settings at runtime but only through the Validate Schema command.

So, if you run the doctrine:schema:validate command, you should get something like :

[Mapping] FAIL - The entity-class Parent mapping is invalid:
* The referenced column name 'username' has to be a primary key column on the target entity class Child.

I hope you find a workaround to keep your logic intact using a primary key as join column.

like image 94
chalasr Avatar answered Oct 03 '22 20:10

chalasr