Doctrine 原则2-无法保存一对多自参考关系

Doctrine 原则2-无法保存一对多自参考关系,doctrine,one-to-many,categories,self,persist,Doctrine,One To Many,Categories,Self,Persist,我在保存一对多的自引用关系时遇到问题,父项和子项都正确地保存在数据库中,但是我为子项设置了parent_id null。 我遵循教义的例子。。。但不知道 namespace CD\Entity; /** * @Entity */ class Category { /** * @Id * @Column(type="integer") * @GeneratedValue(strategy="IDENTITY") */ private $id; /** @Column(type="st

我在保存一对多的自引用关系时遇到问题,父项和子项都正确地保存在数据库中,但是我为子项设置了parent_id null。 我遵循教义的例子。。。但不知道

namespace CD\Entity;
/**
 * @Entity
 */

class Category {


/**
* @Id 
* @Column(type="integer")
* @GeneratedValue(strategy="IDENTITY")
*/
private $id;

/** @Column(type="string",length=50) */
private $name;


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

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


// setters and getters ...
}

我的控制器在这里:

public function insertAction()
{

    $cm = new CD\Entity\Category();
    $cc = new CD\Entity\Category();

    $cm->name = 'mainCat';
    $cc->name = 'childCat';

    $cm->children = array($cc);

    $this->_em->persist($cm);
    $this->_em->flush();        

}

我真的不知道我做错了什么

你试过了吗,特别是扩展版?这样做非常简单。

您需要持久化所有实体。 运行后(假设您使用条令)

条令:生成:实体CD/实体

您将有一个名为“Category->addChildren”的函数,该函数应用于将子对象添加到现有的类别实体中

试试这个:

public function insertAction()
{

    $cm = new CD\Entity\Category();
    $cc = new CD\Entity\Category();

    $cm->setName('mainCat');
    $cc->setName('childCat');

    $cm->addChildren($cc);

    $this->_em->persist($cm);        
    $this->_em->persist($cc);        

    $this->_em->flush();        

}