Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

php - Avoid lazy loading Doctrine Symfony2

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

User owns Avatar with a OneToOne relation.

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.

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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")
 */

See the documentation for YAML or other configuration examples.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...