PHP Doctrine - loading related records

Using Doctrine PHP

If I have a user with many and many relationships with a model address, and each address has a foreign key for an address type (home, office). Doctrine does not automatically load related records for this type of address.

$user = Doctrine::getTable('User')->findOneById(1); // bob
echo $user->Address[0]->address_type_id; // 4
echo isset($user->Address[0]->AddressType); // false
$user->Address[0]->refreshRelated(); // or $user->Address[0]->loadReference('AddressType');
echo isset($user->Address[0]->AddressType); // true
echo $user->Address[0]->AddressType->name; // office

      

Not sure if this is a bug or not in doctrine or my model.

But is this the best way to load related models beyond one level or is there another way to achieve the same result?

+2


source to share


2 answers


Have you just tried to join you in a relationship one by one? Works really well if you have the right relationship.

$user = Doctrine::getTable('User')
  ->createQuery('u')
  ->leftJoin('u.Address a')
  ->leftJoin('a.AddressType t')
  ->findOneById(1);

      



You also get rid of your db 2 sql queries over your example.

+3


source


You say you cannot do this:

echo $user->Address[0]->AddressType->name;

      



If you try this without isset, Doctrine must check to set the value before automatically fetching it for you.

+2


source







All Articles