Reputation: 219
I'm developing a project with Symfony2 LTS and need to create Entities for doctrine. In my database model I have a OneToMany relation, that is part of the PK.
Parent
+-------+--------------+-----+----------------+
| Field | Type | Key | Extra |
+-------+--------------+-----+----------------+
| id | int(11) | PRI | auto_increment |
| name | varchar(255) | | |
+-------+--------------+-----+----------------+
MyChild
+--------------+---------+-----+----------------+
| Field | Type | Key | Extra |
+--------------+---------+-----+----------------+
| id | int(11) | PRI | auto_increment |
| foreignId | int(11) | PRI | |
| other_fields | text | | |
+--------------+---------+-----+----------------+
When I create a PHP Entity class only with id as @ORM\Id
tehre are no Problems, but when I try to add the ManyToOne as Id I get an error
[Doctrine\ORM\Mapping\MappingException]
Single id is not allowed on composite primary key in entity MyBundle\Entity\MyChild
The Php class looks like this:
class MyChild
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var MyParent
*
* @ORM\Id
* @ORM\ManyToOne(targetEntity="MyParent", inversedBy="childs")
* @ORM\JoinColumn(name="foreignId", referencedColumnName="id")
*/
private $parent;
Upvotes: 2
Views: 2054
Reputation: 1087
You should remove the @ORM\Id from the $parent and create a UniqueConstraint for $id and $parent.
/**
* @ORM\Table(uniqueConstraints={
* @ORM\UniqueConstraint(
* columns={"id", "foreignId"}
* )
* })))
*/
class MyChild
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var MyParent
*
* @ORM\ManyToOne(targetEntity="MyParent", inversedBy="childs")
* @ORM\JoinColumn(name="foreignId", referencedColumnName="id")
*/
private $parent;
Upvotes: 3