学说自我参考实体关系会引发错误



我在学说中有一个自我引用实体,但是当我试图坚持下去时,我一直在遇到以下错误:

PHP Catchable fatal error:  Object of class Category could not be converted to string in vendor/doctrine/dbal/lib/Doctrine/DBAL/Statement.php on line 165

示例:

$category1 = new Category();
$category1->setName("Foo");
$category1->setParent( NULL );
$category2 = new Category();
$category2->setName("Bar");
$category2->setParent( $category1 );
$manager->persist( $category1 );
$manager->persist( $category2 );
$manager->flush();

我的实体看起来像这样:

/**
 * @ORMTable(name="categories")
 * @ORMEntity
 */
class Category {
    /**
     * @ORMId
     * @ORMGeneratedValue(strategy="AUTO")
     * @ORMColumn(type="integer")
     */
    protected $id;
    /**
     * @ORMColumn(type="string", length=64, unique=true)
     */
    protected $name;
    /**
     * @ORMColumn(nullable=true)
     * @ORMManyToOne(targetEntity="Category", inversedBy="children")
     * @ORMJoinColumn(name="parent_id", referencedColumnName="id")
     */
    protected $parent;
    /**
     * @ORMOneToMany(targetEntity="Category", mappedBy="parent")
     */
    protected $children;
    public function __construct()
    {
        $this->children = new ArrayCollection();
    }
    public function getId()
    {
        return $this->id;
    }
    public function getName()
    {
        return $this->name;
    }
    public function setName( $name )
    {
        $this->name = $name;
        return $this;
    }
    public function getParent()
    {
        return $this->parent;
    }
    public function setParent( Category $parent = NULL )
    {
        $this->parent = $parent;
        return $this;
    }
    public function getChildren()
    {
        return $this->children;
    }
    public function setChildren( ArrayCollection $children )
    {
        $this->children = $children;
        return $this;
    }
}

我已经搜索过搜索并将我的代码与其他示例进行了比较,但我似乎找不到问题。我显然忽略了什么,但是什么?

尝试使用

/**
 * @ORMManyToOne(targetEntity="Category", inversedBy="children")
 * @ORMJoinColumn(name="parent_id", referencedColumnName="id", nullable=true)
 */
protected $parent;

,但我也建议您在父列上设置 ondelete =" set null" ,如下:

/**
 * @ORMManyToOne(targetEntity="Category", inversedBy="children")
 * @ORMJoinColumn(name="parent_id", referencedColumnName="id", onDelete="SET NULL")
 */
public $parent;

我知道这不是问题的一部分,但是您可能会在不久的将来需要此问题。如果您希望 children 列以用户可以选择的顺序为您提供类别喜欢:

/**
 * @ORMOneToMany(targetEntity="Category", mappedBy="parent")
 * @ORMOrderBy({"order" = "ASC"})
 */
public $children;

相关内容

  • 没有找到相关文章

最新更新