grimmlink
grimmlink

Reputation: 33

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'
    ))
;

Upvotes: 3

Views: 2918

Answers (1)

Elnur Abdurrakhimov
Elnur Abdurrakhimov

Reputation: 44831

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.

Upvotes: 2

Related Questions