MANY_MANY relations with additional fields

Hello,

I’m trying to retrieve related data with an AR MANY_MANY relation but I don’t know exactly how to do it. This is what I have:

There is a table event and user. To define which users will attend an event I have a table event_user with the event and user id. But in this table, apart from the event and user id, there is an extra field ‘state’ that doesn’t interfere in the relationship, it’s just additional information. The idea is that users request to attend an event, and this request can be approved or rejected.

In the Event model I have the following relationship:


public function relations(){

   return array(

     'attendees' => array (self::MANY_MANY, 'User', 'event_user(event_id, user_id)')

   );

}



when I load an event, I have all the attendees of this event with


$event->attendees;

But I have no idea how to get the corresponding ‘state’ field in the table ‘event_user’ for each of those attending users. I want to know which users want to attend to an event and if they have been approved or rejected.

I hope you can help me.

Thanks!

If you have few states, you can set some additional relations with conditions:


public function relations(){

   return array(

     'attendees' => array (self::MANY_MANY, 'User', 'event_user(event_id, user_id)','condition'=>'`state`=1'),

     'absentees' => array (self::MANY_MANY, 'User', 'event_user(event_id, user_id)','condition'=>'`state`=0',),

   );

}

or generate a new model for event_user table or a new HAS_MANY relation between event and event_user.

Read this about relational query with through.

/Tommy

Thank you so much!!!

Finally I’ve created a model for event_user table so I can get the status and the corresponding user model.

Thanks ;)