Commit a58bec12 authored by zYne's avatar zYne

--no commit message

--no commit message
parent 1de19626
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
++ Many-to-Many relations ++ Many-to-Many relations
+++ Creating a new link +++ Creating a new link
Lets say we have two classes User and Group which are linked trhough a GroupUser association class. When working with transient (new) records the fastest way for adding a User and couple of Groups for it is: Lets say we have two classes User and Group which are linked trhough a GroupUser association class. When working with transient (new) records the fastest way for adding a User and couple of Groups for it is:
<code type='php'> <code type="php">
$user = new User(); $user = new User();
$user->name = 'Some User'; $user->name = 'Some User';
$user->Group[0]->name = 'Some Group'; $user->Group[0]->name = 'Some Group';
...@@ -11,7 +11,7 @@ $user->save(); ...@@ -11,7 +11,7 @@ $user->save();
</code> </code>
However in real world scenarious you often already have existing groups, where you want to add a given user. The most efficient way of doing this is: However in real world scenarious you often already have existing groups, where you want to add a given user. The most efficient way of doing this is:
<code type='php'> <code type="php">
$gu = new GroupUser(); $gu = new GroupUser();
$gu->user_id = $userId; $gu->user_id = $userId;
$gu->group_id = $groupId; $gu->group_id = $groupId;
...@@ -22,16 +22,18 @@ $gu->save(); ...@@ -22,16 +22,18 @@ $gu->save();
While the obvious and convinient way of deleting a link between User and Group would be the following, you still should *NOT* do this: While the obvious and convinient way of deleting a link between User and Group would be the following, you still should *NOT* do this:
<code type='php'> <code type="php">
$user = $conn->getTable('User')->find(5); $user = $conn->getTable('User')->find(5);
$user->GroupUser $user->GroupUser
->remove(0) ->remove(0)
->remove(1); ->remove(1);
</code> </code>
This is due to a fact that $user->GroupUser loads all group links for given user. This can time-consuming task if user belongs to many groups. Even if the user belongs to few groups this will still execute an unnecessary SELECT statement.
The right way to delete links between many-to-many associated records is by using the DQL DELETE statement. Convenient and recommended way of using DQL DELETE is trhough the Query API. The right way to delete links between many-to-many associated records is by using the DQL DELETE statement. Convenient and recommended way of using DQL DELETE is trhough the Query API.
<code type='php'> <code type="php">
$deleted = Doctrine_Query::create() $deleted = Doctrine_Query::create()
->delete() ->delete()
->from('GroupUser') ->from('GroupUser')
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment