我在Doctrine中有一个自引用实体,但是当我试图坚持它时,我一直收到以下错误:
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();
我的实体看起来像这样:
/**
* @ORM\Table(name="categories")
* @ORM\Entity
*/
class Category {
/**
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
* @ORM\Column(type="integer")
*/
protected $id;
/**
* @ORM\Column(type="string", length=64, unique=true)
*/
protected $name;
/**
* @ORM\Column(nullable=true)
* @ORM\ManyToOne(targetEntity="Category", inversedBy="children")
* @ORM\JoinColumn(name="parent_id", referencedColumnName="id")
*/
protected $parent;
/**
* @ORM\OneToMany(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;
}
}
我使用Google搜索并将我的代码与其他示例进行比较,但我似乎无法发现问题。我显然忽略了什么,但是什么?
答案 0 :(得分:3)
尝试使用
/**
* @ORM\ManyToOne(targetEntity="Category", inversedBy="children")
* @ORM\JoinColumn(name="parent_id", referencedColumnName="id", nullable=true)
*/
protected $parent;
但我还建议您在父列上设置 onDelete =“SET NULL”,如下所示:
/**
* @ORM\ManyToOne(targetEntity="Category", inversedBy="children")
* @ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="SET NULL")
*/
public $parent;
我知道这不是问题的一部分,但你可能会在不久的将来需要它。如果您希望 children 列按照用户可以选择的顺序为您提供类别,您可能需要添加名为 order 的整数列并定义 children 像这样:
/**
* @ORM\OneToMany(targetEntity="Category", mappedBy="parent")
* @ORM\OrderBy({"order" = "ASC"})
*/
public $children;