10.04.2018 Views

Doctrine_manual-1-2-en

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

Listing<br />

10-49<br />

// test.php<br />

// ...<br />

$user->refresh();<br />

Refreshing relationships<br />

The <strong>Doctrine</strong>_Record::refresh() method can also refresh the already loaded record<br />

relationships, but you need to specify them on the original query.<br />

First lets retrieve a User with its associated Groups:<br />

Listing<br />

10-50<br />

// test.php<br />

// ...<br />

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

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

->leftJoin('u.Groups')<br />

->where('id = ?');<br />

$user = $q->fetchOne(array(1));<br />

Now lets retrieve a Group with its associated Users:<br />

Listing<br />

10-51<br />

// test.php<br />

// ...<br />

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

->from('Group g')<br />

->leftJoin('g.Users')<br />

->where('id = ?');<br />

$group = $q->fetchOne(array(1));<br />

Now lets link the retrieved User and Group through a UserGroup instance:<br />

Listing<br />

10-52<br />

// test.php<br />

// ...<br />

$userGroup = new UserGroup();<br />

$userGroup->user_id = $user->id;<br />

$userGroup->group_id = $group->id;<br />

$userGroup->save();<br />

You can also link a User to a Group in a much simpler way, by simply adding the Group to<br />

the User. <strong>Doctrine</strong> will take care of creating the UserGroup instance for you automatically:<br />

Listing<br />

10-53<br />

// test.php<br />

// ...<br />

$user->Groups[] = $group;<br />

$user->save()<br />

Now if we call <strong>Doctrine</strong>_Record::refresh(true) it will refresh the record and its<br />

relationships loading the newly created refer<strong>en</strong>ce we made above:<br />

Listing<br />

10-54<br />

// test.php<br />

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

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

Saved successfully!

Ooh no, something went wrong!