2
votes

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;
1
It makes no sense for MyChild to have a compound primary key. Show how you made foriegnId or maybe look at some sql basics.Cerad
I'd like to start the incrementation of the Id of the child for each parent, so I need it as primary key. For example Parent 1 can have child 1-1, 1-2, ... and Parent 2 can have 2-1, 2-2, 2-3Georg
And how exactly is that going to work with Child::id being an auto-inc? Messing around with id's is almost always more trouble that it is worth. What happens if 2-2 gets deleted? Going to renumber everything?Cerad

1 Answers

3
votes

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;