php - Symfony 和 Doctrine : lazy loading is not working

标签 php symfony doctrine-orm lazy-loading eager-loading

使用 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/

相关文章:

php - 需要帮助查找 Doctrine 2 xml 映射文件中的错误

php - 重定向而不更改浏览器 url

javascript - PHP minify 函数似乎破坏了内联 JS?

php - 如何在分页中添加省略号?

php - 使用 GET 参数在 Symfony 5 中生成 URL

postgresql - Heroku 上的 Sylius,获取 "phpcr_workspaces"不存在

symfony - 使用 REPLACE INTO 而不是 INSERT INTO 将 Doctrine2 保留到数据库

从用户代理检测设备(移动)是什么的 php 脚本?

php - 如果已经在其他应用程序的主域上登录,如何使用 symfony 安全登录到子域?

php - Doctrine 和 PDO 没有给出相同的结果