使用 Symfony 2.8。
我有社区和MenuItem实体,其中社区有一个一组菜单项。
Community.php 具有以下代码:
...
/**
* @ORM\OneToMany(targetEntity="MenuItem", mappedBy="community", fetch="LAZY")
* @ORM\OrderBy({"sequence" = "ASC"})
*/
private $menuItems;
...
MenuItem.php具有以下代码:
...
/**
* @var Community
*
* @ORM\ManyToOne(targetEntity="Community", inversedBy="menuItems")
*/
private $community;
...
重点是,当我使用时:
$menuItems = $community->getMenuItems();
$menuItems
变量将是一个空集合。
可以通过设置 fetch="EAGER"
而不是 fetch="LAZY"
来解决这个问题,因为这样 $menuItems
> Category 实体的属性立即加载。
懒惰与渴望 ( source ) :
Whenever you have a managed entity instance at hand, you can traverse and use any associations of that entity that are configured LAZY as if they were in-memory already. Doctrine will automatically load the associated objects on demand through the concept of lazy-loading.
Whenever you query for an entity that has persistent associations and these associations are mapped as EAGER, they will automatically be loaded together with the entity being queried and is thus immediately available to your application.
重点是,虽然 EAGER 加载按预期工作,但 LAZY 加载似乎根本不起作用。知道为什么吗?
最佳答案
这似乎可以加载惰性关系。
$logs = $entity->getLogs(); // lazy relationship
$this->getDoctrine()->getManager()->initializeObject($logs);
$logs 现在将填充。
初始化对象的文档:
Helper method to initialize a lazy loading proxy or persistent collection.
关于php - Symfony 和 Doctrine : lazy loading is not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36620607/