cakephp - 不同的有很多通过关系
我想知道这是否可以与 a has much throughContents
contents orgs folders
id id id
name name title
link
join table - folder_elements
id
element_id
order
通过folder_elements 有很多文件夹
orgs 通过folder_elements 有很多文件夹
所以我的问题是,是否可以使用 element_id 来存储 content.id 或 org.id ?
亚历克斯
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您所描述的是一种 HABTM(HasAndBelongsToMany)关联。您可以按照您的建议定义模型间关联,但存在一个相当严重的设计缺陷:您如何解释将相同 ID 用于
orgs
记录和contents 的情况
记录,并希望将它们与同一文件夹
记录关联?在连接表中区分两者是不可能的。有很多方法可以解决这个问题,但它们需要更多的程序逻辑或更杂乱的数据库模式,这给可维护性带来了挑战。
更优雅、更强大的解决方案是合理化您的数据库结构。如果没有迫切需要使用一个联接表来规则所有内容,您可以像这样设计模型关联:
Content hasMany ContentsFolder ownsTo Folder
Folder hasMany ContentsFolder owningTo Content
Org hasMany OrgsFolder ownsTo Folder
Folder hasMany OrgsFolder owningTo Org
这是显式定义的 HABTM 关联的内部结构,因此您可以在连接表中定义字段。您的
contents
和folders
表将保持不变,但您的两个连接表将如下所示:不幸的是,是的,这需要定义五个模型而不是三个,但这些是CakePHP 对象关系建模的局限性。
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 acontents
record, and wish to associate them with the samefolder
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
andfolders
tables 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.