简体   繁体   中英

How to avoid symfony2 to automatically load one-to-one relationship

I have a User class which have a One-to-One association with another entity Result

Everything is working fine but anytime I load a set of users, i can see in the profiler that for each user symfony makes a query to load his result.

I don't need the result everywhere, and i manually retrieve it when i need. I came to believe that symfony loads one-to-one relations automatically with the entity but didn't find out how to avoid it.

My classes :

class User extends BaseUser {
    /**
     * @ORM\OneToOne(targetEntity="Result", mappedBy="user", cascade={"all"}, orphanRemoval=TRUE)
     */
     protected $result;
}

class Result {
    /**
     * @ORM\OneToOne(targetEntity="User", inversedBy="result")
     * @ORM\JoinColumn(name="id_user", referencedColumnName="id")
     */
    protected $user;
 }

----- EDIT -----

I found out that it only happen when the User entity is loaded in a formbuilder :

$builder
    ->add('user', 'entity', array(
        'class' => 'ThemBaseBundle:User',
        'query_builder' => function($repository) {
            return $repository->createQueryBuilder('a')
            ->orderBy('a.lastName', 'ASC');
        },
        'property' => 'fullName'
    ))
;

I'm not sure, but probably one-to-one relations are fetched eagerly by default. Try switching the fetching strategry to lazy. See this section for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM