Best method for saving MANY_MANY records

I’ve been searching/reading through the forum for a couple of days now, trying to figure out the best way to save records that are part of a MANY_MANY relationship.

I found a couple of posts describing ways to accomplish this, but one involved an extension and the other was a little difficult for me to follow.

I was hoping to find a way to save these records without having to install an extension (for the sake of learning how to do it with Yii).

I am creating a simple to-do list application for the purpose of learning more about Yii. In my project, there are Users and Projects. Users can have many projects, and projects can have many users.

When I create a new project, I’m having trouble figuring out the best way to associate it with the correct user. I don’t have a model for the association/join table, so I’m not sure how to insert records into that table if ActiveRecord isn’t aware of it (except through the composite key definitions in each model’s relations() method).

Can anyone offer suggestions for this, please?

Thanks in advance!

Tom

You could add methods like addUser()/deleteUser() to your Project model that handle creation/deletion of the AR for the connecting table. That helps to keep your controller code clean.

Thanks man, that sounds good.

For one of them, I ended up putting the code to update the join table (with raw SQL) in the model’s after save method.

Is there any way to add/update the MANY_MANY records using ActiveRecord?

Not sure if i understand. You can use AR in the addUser() method.

No problem - I was just wondering if there is a way to create a User record in the database within the addUser() method using ActiveRecord’s methods and model relationships rather than just writing the SQL needed to add the record in the join table.

Simply create a AR for your join table. Then you can do like this:


public function addUser($userid) {

  $user=new ProjectUser;

  $user->project_id=$this->id;

  $user->user_id=$userid;

  return $user->save();

}

Sweet, that’s what I was hoping to find. Thanks very much for your help!

Tom