Friday, December 3, 2010

YII » On Many Many Relationships

1. If you have a composite primary key, make sure you override the primaryKey method in your model, like this:

public function primaryKey()
{
  return array('field_one', 'field_two');
}

2. Now, you cannot generate Gii CRUD operations when you have a composite primary key, but you can make a model and a controller and forms, so you can just do some of it manually.

You can do something like this in your controller, with a (blog) Posting table with many-many related tags:

public function actionDelete($id)
{
  $posting_id=$_GET['posting_id'];

  $pk = array('posting_id'=>$posting_id, 'tag_id'=>$id);
  PostingTag::model()->deleteByPk($pk);
}

4 comments:

  1. This is GOLD! So many Yii users run into problems when it comes to MANY_MANY relationships. THANK YOU SO MUCH for shedding some light on the issue!!!

    ReplyDelete
  2. Just set the $id param of actionDelete to expect the pk array (or alternatively add a 2nd param to represent $posting_id, removes some needless code).

    My recommendation:

    // $_GET looks like
    // $_GET = array('posting_id'=>1234,'tag_id'=>1234);
    // So in your delete link, you would pass 'id'=>$model->getPrimaryKey()

    public function actionDelete(array $id)
    {
    PostingTag::model()->deleteByPk($id);
    }

    ReplyDelete
  3. I am struggling to do this from yesterday. You have saved my time. Great job and thanks alot.

    ReplyDelete