具有此实体的外键的doctrine实体

时间:2012-09-04 11:21:05

标签: orm symfony doctrine doctrine-orm

我有一个简单的递归类表:

id
name
parent_id - is a link to id, NULL - for root categories

我需要创建一个包含外键的表。我的班级没有创建这个密钥。如何使用“doctrine:schema:create”更改此类以使用外键创建表?我尝试过:

<?php
namespace Test\BackEndBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="category")
 */
class Category
{
    /**
     * @ORM\Id
     * @ORM\Column(type="bigint", length=20)
     * @ORM\GeneratedValue(strategy="AUTO")
     * @var int
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length="255")
     * @var string
     */
    protected $name;

    /**
     * @ORM\Column(name="parent_id", type="bigint", length=20, nullable="true")
     * @ORM\OneToMany(targetEntity="Category")
     * @ORM\JoinColumn(name="id", onDelete="CASCADE", onUpdate="CASCADE")
     * @var int
     */
    protected $parentId;

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }
}

1 个答案:

答案 0 :(得分:7)

你用ManyToOne颠倒了OneToMany!

见这里:http://docs.doctrine-project.org/en/2.0.x/reference/association-mapping.html#one-to-many-self-referencing

事实上,你想要多个子类别可以有一个父猫!

你需要什么:

/**
 * @OneToMany(targetEntity="Category", mappedBy="parent")
 */
private $children;

/**
 * @ManyToOne(targetEntity="Category", inversedBy="children")
 * @JoinColumn(name="parent_id", referencedColumnName="id")
 */
private $parent;
// ...

public function __construct() {
    $this->children = new \Doctrine\Common\Collections\ArrayCollection();
}

您可以为$ parentId替换$ parent(对于mappedBy =“parentId”替换mappedBy =“parent”),但这不是一个好的编码约定^^