Need help with deleting entries from many-many table.

Hello!

I’ve got some problems with deleting entries from many-many table. I’ve got three tables in my DB: User, Group an GroupUser.

Adding entries to GroupUser works like a charm:

Yii::app()->db->createCommand("INSERT INTO GroupUser(id_group, id_user) VALUES($id_group, $id_user)")->execute();

Unfortunately, deleting doesnt work:

Yii::app()->db->createCommand("DELETE FROM GroupUser WHERE id_group = $id_group AND id_user = $id_user")->execute();

Yii doesn’t show any errors, operation is successful. But entry from my database isn’t deleted :(

My relations in Group model:

return array(

‘users’=>array(self::MANY_MANY, ‘User’, ‘GroupUser(id_group, id_user)’),

‘usersCount’=>array(self::STAT, ‘User’, ‘GroupUser(id_group, id_user)’),

);

My relations in User model:

return array(

‘groups’=>array(self::MANY_MANY, ‘Group’, ‘GroupUser(id_user, id_group)’),

‘groupsCount’=>array(self::STAT, ‘Group’, ‘GroupUser(id_user, id_group)’),

);

What am I doing wrong?

Regards,

PK

You are using a quite strange approach.

You are absolutely not using the AR support of Yii.

The insertion can be done like that:




$GroupUser=new GroupUser;

$GroupUser->id_group=$id_group;

$GroupUser->id_user=$id_user;

$GroupUser->save();



And the deletion like that:




GroupUser::model()->find("id_group = '$id_group' AND id_user = '$id_user'")->delete();



Like that you are using AR.

when you are writing your own sql, is better to use ‘$id_user’, with ’