2017-06-19 92 views
0

我使用下面的代码在我的模型学说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设置的获取模式有关?

+0

实验? –

+0

感谢您的回复。我实际上必须执行 $ item-> getChildren() - > GetValues(); 得到数组 – Dimitris

+0

这听起来像是问题;除非我很疯狂,否则你会想要一个'DoctrineCollection'而不是从该getter返回的'array' ... –

回答

0

答案是懒加载

如果不更改型号,您必须使用

$ i透射电镜>的getChildren() - >的GetValues();

否则,你将不得不与是否`$父 - >的getChildren()`返回的项目的`DoctrineCollection`预期为注释积极加载

0

ArrayCollection它有助于提高性能,添加延迟加载,排序和匹配(如果数据库还没有加载数据,如果您已经访问过它,则在数据库上)。

个人而言,我真的很喜欢与ArrayCollection的工作,但你可以摆脱掉它更新以下列方式你的实体:

/** 
* @return array 
*/ 
public function getChildren() 
{ 
    return $this->children->toArray(); 
} 

过滤集合: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-associations.html#filtering-collections