Displaying many to many relations

Hi all,

A basic question I’m sure, but after exploring many to many relationships all day my head is total mush.

I’ve used the behaviors to easily add and remove relations using a join table. Basically I have the following

Table: Resource

  • id (PK)

  • name

Table: Service

  • id (PK)

  • name

Table Resource_Service_Mapping

  • resource_id (FK)

  • service_id (FK)

I can get data in this table, and it’s populating and it’s all awesome… Buttttt…

On each of the Resources form, and the Service form, I want to provide the ability to have a table of all the resources or services and allow users to have an ajax link to either create or remove that relationship.

ie. I want a form that looks like the following




           Service1     Service2    Service3           

Room 1          YES         YES        NO 

Room 2          NO          NO         NO

Room 3          YES         NO         NO



ie. I want the full list of all the services on the resources (room) form, and then check the value of the mapping table when the value is toggled.

However I am not sure how to lookup the value from the relation table.

In relations on Services I have

‘resources’=>array(self::MANY_MANY, ‘Resource’, ‘services_resources_mapping(service_id, resource_id)’),

and in relations on Resources I have

‘services’=>array(self::MANY_MANY, ‘Resource’, ‘services_resources_mapping(resource_id, service_id)’),

However I just don’t know how to apply the filter to add a query on services? Any ideas… please?? :)

I guess this needs to be a virtual value or something that’s set when the query is performed?

Ideally I want this loaded when the query is performed so I don’t need to do a query per record… Hmm…

Have you been successfull with your problem? I am facing the same problem and would be happy for any solution!!

Thx :)

Have not tried it yet but this might be the solution.

Use the sql to find all the result. Use the inner join for your purpose or any other join that fits your circumstances. Create model for Resource_Service_Mapping as well.




$model = new Services();

$sql = "";

$resultant = $model -> findAllBySql($sql);


foreach($resultant as $obj) {

echo $obj -> resources -> id; // for id of resources

echo $obj - > id; // id of services

}



This is the basic idea.

Try it!!

Thx for the answer! I guess for your solution we would need another foreach in the already given foreach, because resources is an array, or did I miss something?

Anyway this seems to me like a very old school way of displaying that. Isn’t there an easier way using some Yii techniques (like CGridView for example)?

You can ofcourse use gridview. I am just showing you how to access it. I hope you can find in the documentation of Yii about CGridview.