简体   繁体   中英

ManyToOne as ID on doctrine (symfony2)

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;

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM