tags:

views:

703

answers:

2

Using Doctrine PHP

If I have a user with a many to many relationship with the model address and each address has a foreign key to a address type (home, office). Doctrine doesn't automatically load the related records for that address type.

$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 deep or is there another way to achieve the same result?

+3  A: 

Have you simply tried joining you relations one by one? Works pretty well, if you relations are set up correct.

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

You also spare your db 2 sql queries, compared to your example.

virtualize
+2  A: 

Are you saying you can't do this:

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

If you try that without the isset, Doctrine should check to see that the value is set before retrieving it for you automatically.

Chris Williams