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_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
orgsrecord and acontentsrecord, and wish to associate them with the samefolderrecord? 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 FolderFolder hasMany ContentsFolder belongsTo ContentOrg hasMany OrgsFolder belongsTo FolderFolder hasMany OrgsFolder belongsTo OrgThis is the internal structure of a HABTM association defined explicitly so you can define fields in the joining table. Your
contentsandfolderstables would remain the same, but your two joining tables would look like:Unfortunately, yes, this would require defining five models instead of three, but such are the limitations of CakePHP’s object-relational modelling.