开发者

cakephp - a different has many through relationship

I was wondering if this is possible to do with a has many through

contents       orgs            folders
 id             id              id
 name           name            title
 link

join table - folder_elements
              id
              element开发者_StackOverflow中文版_id
              order

contents has many folders through folder_elements

orgs has many folders through folder_elements

So my question is, is it possible to use element_id to store the content.id or the org.id ?

Alex


What you're describing is a sort of HABTM (HasAndBelongsToMany) association. You could define the inter-model associations as you suggest, but there's a pretty significant design flaw: how would you account for a situation where the same ID is used for an orgs record and a contents record, and wish to associate them with the same folder record? It would be impossible to differentiate between the two in your joining table.

There are a number of ways to work around this, but they require more program logic or a more disorganised database schema that presents challenges in maintainability.

The more elegant, robust solution is to rationalise your database structure. If there's no pressing need to have One Join Table to Rule Them All, you could design your model associations like this:

  • Content hasMany ContentsFolder belongsTo Folder
  • Folder hasMany ContentsFolder belongsTo Content
  • Org hasMany OrgsFolder belongsTo Folder
  • Folder hasMany OrgsFolder belongsTo Org

This is the internal structure of a HABTM association defined explicitly so you can define fields in the joining table. Your contents and folders tables would remain the same, but your two joining tables would look like:

contents_folders
-> id
-> content_id
-> order

orgs_folders
-> id
-> org_id
-> order

Unfortunately, yes, this would require defining five models instead of three, but such are the limitations of CakePHP's object-relational modelling.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜