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 8: Working with Models 108<br />

Listing<br />

8-31<br />

// test.php<br />

// ...<br />

$user = new User();<br />

$user->username = 'Some User';<br />

$user->Groups[0]->username = 'Some Group';<br />

$user->Groups[1]->username = 'Some Other Group';<br />

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

However in real world sc<strong>en</strong>arios you oft<strong>en</strong> already have existing groups, where you want to<br />

add a giv<strong>en</strong> user. The most effici<strong>en</strong>t way of doing this is:<br />

Listing<br />

8-32<br />

// test.php<br />

// ...<br />

$groupUser = new GroupUser();<br />

$groupUser->user_id = $userId;<br />

$groupUser->group_id = $groupId;<br />

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

Deleting a Link<br />

The right way to delete links betwe<strong>en</strong> many-to-many associated records is by using the DQL<br />

DELETE statem<strong>en</strong>t. Conv<strong>en</strong>i<strong>en</strong>t and recomm<strong>en</strong>ded way of using DQL DELETE is through the<br />

Query API.<br />

Listing<br />

8-33<br />

// test.php<br />

// ...<br />

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

->delete('GroupUser')<br />

->addWhere('user_id = ?', 5)<br />

->whereIn('group_id', array(1, 2));<br />

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

Another way to unlink the relationships betwe<strong>en</strong> related objects is through the<br />

<strong>Doctrine</strong>_Record::unlink method. However, you should avoid using this method unless<br />

you already have the par<strong>en</strong>t model, since it involves querying the database first.<br />

Listing<br />

8-34<br />

// test.php<br />

// ...<br />

$user = <strong>Doctrine</strong>_Core::getTable('User')->find(5);<br />

$user->unlink('Group', array(1, 2));<br />

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

You can also unlink ALL relationships to Group by omitting the second argum<strong>en</strong>t:<br />

Listing<br />

8-35<br />

// test.php<br />

// ...<br />

$user->unlink('Group');<br />

While the obvious and conv<strong>en</strong>i<strong>en</strong>t way of deleting a link betwe<strong>en</strong> User and Group would be<br />

the following, you still should NOT do this:<br />

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

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

Saved successfully!

Ooh no, something went wrong!