Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine 2 Lazy loading fail

I have two entities, user and client, one client can have many users.

Often I want to have a user entity and lazy load the client but for some reason the client proxy doesn't load itself when I try to access its properties.

If I dump the data like this \Doctrine\Common\Utils\Debug::log($user->client); it will output the client proxy with its client id.

If I change the fetching policy to "EAGER" I will get the client entity intact but I don't always need the client entity when I access the users so I much rather use LAZY loading if its possible.

EDIT

When I later on do this:

$user->client->name

I will get null back even though my proxy got a client id.

This are my two relations (inside the annotatation):

// user annotation

/**
 * @var Entities\Client
 *
 * @ManyToOne(targetEntity="Client", inversedBy="users", fetch="LAZY")
 */
private $client;

// client annotation

/**
 * @var Entities\User
 *
 * @OneToMany(targetEntity="User", mappedBy="client", cascade={"all"}, fetch="LAZY")
 */
private $users;

EDIT

I found out why it didn't work, all of my annotations extended a base annotation, the base annotation then had a getter and a setter that failed when used in the proxy class.

like image 754
Dennis Avatar asked Apr 24 '11 18:04

Dennis


1 Answers

You should never define properties mapped in Doctrine as public. Instead you should always define them as protected or private, and then access them using getters and setters. This way, Doctrine can define a proxy class that "redefines" those getters and setters (thus allowing lazy loading).

If you access the property directly (as you were doing in $user->client->name), Doctrine has no way to intercept that call.

like image 118
Aurel Avatar answered Sep 26 '22 02:09

Aurel