Avoid lazy loading Doctrine Symfony2

2019-02-06 10:10发布

问题:

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 @ORM\HasLifecycleCallbacks 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 $currentUser = $this->get('security.context')->getToken()->getUser()), but I can't get the avatar with $currentUser->getAvatar() :

var_dump($currentUser->getAvatar());exit;

Output :

object(Proxies\__CG__\Participso\UserBundle\Entity\Avatar)[355]
    public '__initializer__' =>
object(Closure)[348]
    public '__cloner__' =>
object(Closure)[349]
    public '__isInitialized__' => boolean false
    private 'id' (Participso\UserBundle\Entity\Avatar) => int 20
    public 'file' => null
    private 'fileName' (Participso\UserBundle\Entity\Avatar) => null

But if i do

$whatever = $currentUser->getAvatar()->getFileName();
var_dump($currentUser->getAvatar());exit;

Output :

object(Proxies\__CG__\Participso\UserBundle\Entity\Avatar)[355]
    public '__initializer__' =>
object(Closure)[348]
    public '__cloner__' =>
object(Closure)[349]
    public '__isInitialized__' => boolean false
    private 'id' (Participso\UserBundle\Entity\Avatar) => int 20
    public 'file' => null
    private 'fileName' (Participso\UserBundle\Entity\Avatar) => string 'd4e5eadd3757498a22b14ad1f81869c2baf459d3.png'

This is pretty annoying... Does somebody have a clue to avoid this ?

回答1:

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.