How to delete all the records in a MANY_MANY relationship?

E.g. There is a MANY_MANY relationship between A and B, so the models are as followings:




class A extends CActiveRecord

{

  public function relations()

  {

    return array(

      'relation_a_b' => array(self::MANY_MANY, 'B', A_B('a_id','b_id'),

    };

  }

}


class B extends CActiveRecord

{

  public function relations()

  {

    return array(

      'relation_b_a' => array(self::MANY_MANY, 'A', A_B('b_id','a_id'),

    };

  }

}



and the tables in DB are: A, B and A_B. Then here comes the problems: if I want to delete some records in table A, how can I remove the referred records from A_B, or is there any function or parameter can do this?

Hey,

Assuming that you’re using MySQL:

Usually I set this in MySQL by using "on delete cascade" in the foreign table, so the proccess is faster and performed by the database engine

Hope it helps

:)

Hi,

Thank you for the helps. I will set this in MySQL

and how can I delete only the relation in the A_B table?

You can try out wform or eadvancedarbehavior extension. They both supports delete for MANY_MANY.

or you could try

Yii::app()->db->createCommand(‘DELETE FROM {{table}} WHERE <field>=:id’)->execute(array(’:id’=>$the_id));

hope it helps

:)

regards