Update Operation On Model With Many_Many

How am I supposed to handle this?

Let’s say I have a many to many relationship between tables A and B, so I introduce C between them to break the many-many. When I update the db (that is, in the AController::actionUpdate) the entire subset of rows in C relating A to C and back again might have changed. Is that handled automagically, or am I going to have to write code to explicitly hand deleting the current rows in C and inserting new ones?

For example, if I have an A which has three corresponding rows in C, and the user edits A to only include two of those Cs, what do I have to do explicitly in code to handle that?

Depending on what your actually dealing with(not A B C) you can handle removing the relationship between A and B(which I think is C) in a variety of different ways. There are modules for Yii that handle many_many relationships and might do what you want, and here’s one place to look if you’re interested: http://www.yiiframew…/?tag=many_many…

Otherwise you can roll your own code to handle removing instances of "C".

I’ll show you one way to roll your own code that I think is pretty cool. For the sake of a better explanation, let’s assume that you have “User”, and “Group” models, and they are joined by a “UserGroup” model, and you have all relationships setup. Also, we’ll assume when viewing a particular group, that you have a list of the groups related users lazy loaded and displayed in that same view with some custom code below, and an ajaxLink beside each user that calls a controller action which will remove them from the group without reloading the page.


echo "<ul id='group_users_".$group->id."'>";

echo $this->renderPartial('_groupUsers', array('model'=>$model));

echo "</ul>"; 


// $model is currently viewed group, and users is the name of your many_many relationship that I presume you would've had setup in your Group model

$users = $model->users;

foreach($users as $user)


	echo "<li class='group_user' id='group_user_".$user->id."'>";

	echo "<span>" . $user->username . "</span>";

	echo CHtml::ajaxLink( 




















	echo "</li>";



public function actionRemoveUser()


    $userId = $_POST['userId'];

    $groupId = $_POST['groupId'];

    if(!empty($userId) && !empty($groupId))


		if($userGroup = UserGroup::model()->find('user_id=:userId AND group_id=:groupId', array(':userId'=>$userId, ':groupId'=>$groupId)))


 			$userGroup->delete(); // remove relationship between user and group to remove user from the group





[size=“2”]I’ve run out of time here for now, but hopefully this post helps you out in the meantime.[/size]