开发者

CakePHP HTBTM with extra field : Double Logical Relationship : How to construct $this->data in controller on my own

I have HABTM relation between "Event" and "Category" models. But in the bridge table, "categories_events" table, there is an extra field called "is_primary"; meaning and Event is belong to 1 primary category and many secondary categories.

I deployed 1 select box named "primary_event" and checkboxes named "seconday_event[]".

When I submit the form the data comes up like this. $this->data['Event']['primary_event'] -> 4; 开发者_JAVA百科$this->data['Event']['secondary_event'] -> array(1,3,5);

After that, how do I feed those data into the format that Cake recognize and which Model's save function do I call? Please be advised that "is_primary" field must be set to 1 for 'primary_event' row.

Thanks, Moe


As soon as my joining table has anything more than the dual keys (probably event_id and category_id in your case, I create it as a "standalone" model and modify the relationships as follows (again, using your example):

Event -- hasMany --> EventCategory <-- hasMany -- Category
Event <-- belongsTo -- EventCategory -- belongsTo --> Category

There's a little less "magic", but I think the magic begins to break down as soon as you introduce an additional property (i.e. field). This also gives you a little more flexibility for the future. If you've already found a reason to introduce one new property, it seems even more likely that you might find a reason to add more.


The way I understand your requirement, you'll need to create and save records on the categories_events model (You don't need to explicitly code the model unless it has special behaviour - CakePHP is wise enough to understand what you're doing and use a default model structure).

The first create and save will be the primary, then loop over the array for the secondaries. Remember to do a my_model->create() on each iteration.


is_primary is a function of Events, not the HABTM table you are trying to associate it to. The HABTM links the Events and Categories, not events to events. The is_primary should be stored on the Events table. Then you need to associate sub events to their primary event. Here is how to do that.

1- Add the is_primary field to the events table and make it a bool.

2- Add a primary_event_id to the events table. (This will only contain a value if the event is a sub-event.)

3- Create a relationship between events and itself in the Event model. (http://book.cakephp.org/view/851/Multiple-relations-to-the-same-model) This will allow self referencing so you can reference sub-events to their primary event.

Once you get the ID of the event you are interested in, you can run queries to find all of the sub-events:

$this->Event->find('all', array('conditions' => array('primary_event_id' => $id)));

This will return a list of all sub-events.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜