Doctrine ManyToOne w/o a primary ID key

Viewed 2500

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;

    // ....
}
1 Answers
Related