避免延迟加载 Doctrine Symfony2 [英] Avoid lazy loading Doctrine Symfony2

查看:24
本文介绍了避免延迟加载 Doctrine Symfony2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目中有两个实体:用户和头像.

I have two entities in my project : User and Avatar.

用户通过一对一关系拥有头像.

User owns Avatar with a OneToOne relation.

Avatar 是一个具有文件对象和文件名的实体.它使用@ORMHasLifecycleCallbacks 来保存文件或删除它,如 Symfony2 文档.

Avatar is an entity with a file object and a fileName. It uses @ORMHasLifecycleCallbacks to save the file or to remove it as described in the Symfony2 documentation.

在我的控制器中,我想从当前用户中删除 Avatar 实体(我使用 $user = $this->get('security.context')->getToken()->getUser()),但我无法使用 $user->getAvatar() 访问头像:

In my controller, I want to remove the Avatar entity from the current user (I use $user = $this->get('security.context')->getToken()->getUser()), but I can't get to the avatar with $user->getAvatar() :

var_dump($user->getAvatar());

object(AppBundleEntityAvatar)
    private 'id' => int 20
    public 'file' => null
    private 'fileName' => null

但是如果我尝试访问头像的文件名,它会被返回:

But if I try to acces the avatar's fileName, it gets returned :

$filename = $user->getAvatar()->getFileName();
var_dump($user->getAvatar());

object(AppBundleEntityAvatar)
    private 'id' => int 20
    public 'file' => null
    private 'fileName' => string 'myfile.png'

如何获取与我的用户关联的头像?

How can I get the Avatar associated with my user ?

推荐答案

Doctrine docs,您只需要指定要急切的获取行为.

As described in the Doctrine docs, you just need to specify the fetching behavior to be eager.

/**
 * @OneToOne(targetEntity="User", fetch="EAGER")
 * @JoinColumn(name="user_id", referencedColumnName="id")
 */

请参阅 YAML 或其他配置示例的文档.

See the documentation for YAML or other configuration examples.

这篇关于避免延迟加载 Doctrine Symfony2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆