我使用下面的代码在我的模型学说2 - 双向自引用一对多关系不工作
/**
* Many Categories have One Category
* @ORM\ManyToOne(targetEntity="ItemCategory", inversedBy="children")
* @ORM\JoinColumn(name="parent_id", referencedColumnName="id")
*/
public $parent;
/**
* One Category has many Categories
* @ORM\OneToMany(targetEntity="ItemCategory", mappedBy="parent")
*/
public $children;
/**
* ItemCategory constructor.
*/
public function __construct()
{
$this->children = new \Doctrine\Common\Collections\ArrayCollection();
$this->parent_id = 0;
}
/**
* @return ItemCategory
*/
public function getParent()
{
return $this->parent;
}
/**
* @param mixed $parent
*/
public function setParent($parent)
{
$this->parent = $parent;
}
/**
* @return ArrayCollection
*/
public function getChildren()
{
return $this->children;
}
我用这与实体管理器,以获得资源库和使用的findAll()来获取在返回公共属性的json的控制器上使用的所有结果。
$em = $this->getDoctrine()->getManager();
$repository = $em->getRepository("AppBundle:Item\ItemCategory");
$categories = $repository->findAll();
return new JsonResponse(array("item_categories" => $categories));
Symfony没有抛出任何错误,而ManyToOne方面没有问题,并且使用完整对象来表达父属性。
OneToMany方面虽然我试过,但仍然是空的。
结果数组包含看起来像
{ "id": 8, "parent": { "id": 3, "parent": null, "children": {}, "name": "Ανταλλακτικά", "description": "", "meta_description": "", "icon": "cogs" }, "children": {}, "name": "Ποδηλάτων", "description": "", "meta_description": "", "icon": "" },
我寻觅了很多在这里stackexchange和文档上的对象,但我能找到什么工作的。
我希望再次看看我的代码,以防万一我失去了一些明显的东西。感谢您的时间
=========== UPDATE ==================
经过一番更多的调查,看来为儿童返回的对象是PersistentCollection。 这意味着我必须执行
$ item-> getChildren() - > GetValues();
获得实际的孩子
我如何能避免这一点,对房地产直接获取值有什么想法?可能与EAGER设置的获取模式有关?
实验? –
感谢您的回复。我实际上必须执行 $ item-> getChildren() - > GetValues(); 得到数组 – Dimitris
这听起来像是问题;除非我很疯狂,否则你会想要一个'DoctrineCollection'而不是从该getter返回的'array' ... –