10.04.2018 Views

Doctrine_manual-1-2-en

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 10: Compon<strong>en</strong>t Overview 182<br />

Listing<br />

10-87<br />

// test.php<br />

// ...<br />

$userTable = <strong>Doctrine</strong>_Core::getTable('User');<br />

$userTable->setAttribute(<strong>Doctrine</strong>_Core::ATTR_COLL_KEY, 'username');<br />

Now user collections will use the values of name column as elem<strong>en</strong>t indexes:<br />

Listing<br />

10-88<br />

// test.php<br />

// ...<br />

$users = $userTable->findAll();<br />

foreach($users as $username => $user) {<br />

echo $username . ' - ' . $user->created_at . "\n";<br />

}<br />

Note this would only be advisable if the username column is specified as unique in your<br />

schema otherwise you will have cases where data cannot be hydrated properly due to<br />

duplicate collection keys.<br />

Loading Related Records<br />

<strong>Doctrine</strong> provides means for effici<strong>en</strong>tly retrieving all related records for all record elem<strong>en</strong>ts.<br />

That means wh<strong>en</strong> you have for example a collection of users you can load all phon<strong>en</strong>umbers<br />

for all users by simple calling the loadRelated() method.<br />

However, in most cases you don't need to load related elem<strong>en</strong>ts explicitly, rather what you<br />

should do is try to load everything at once by using the DQL API and JOINS.<br />

The following example uses three queries for retrieving users, their phon<strong>en</strong>umbers and the<br />

groups they belong to.<br />

Listing<br />

10-89<br />

// test.php<br />

// ...<br />

$q = <strong>Doctrine</strong>_Query::create()<br />

->from('User u');<br />

$users = $q->execute();<br />

Now lets load phon<strong>en</strong>umbers for all users:<br />

Listing<br />

10-90<br />

// test.php<br />

// ...<br />

$users->loadRelated('Phon<strong>en</strong>umbers');<br />

foreach($users as $user) {<br />

echo $user->Phon<strong>en</strong>umbers[0]->phon<strong>en</strong>umber;<br />

// no additional db queries needed here<br />

}<br />

The loadRelated() works an any relation, ev<strong>en</strong> associations:<br />

Listing<br />

10-91<br />

----------------- Brought to you by

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!