CakePHP:属于多个人的模型,一次一个 [英] CakePHP: Model that belongs to multiple others, one at a time
问题描述
是否有一个简单的解决方案来构建这些关系?
如何设置添加动作?
我知道我可以设置两个连接表并使用HABTM,但是感觉不对。文档仅属于一个其他项目。此外,如果需要,我想能够将关系扩展到更多的模型。
您要查找的内容被称为多态性。基本上,您不是通过单个 other_model_id
字段将模型与固定的其他模型相关联,但是您可以跟踪两个字段: other_model_class
和 other_model_foreign_key
。这样,您可以将文档
与类:User,id:42
在一种情况下关联, class:Course,id:42
另一个。有一个面包店行为,这应该是一个开始的好地方。
I have three tables: "users", "courses" and "documents". I would like to upload documents to users as well as to courses, so I would need two belongsTo-relations for the Document model. Some belong to one model, some to the other.
Is there a simple solution to construct these relations?
How could I set up the "add"-actions?
I know I could set up two join tables and use HABTM, but that doesn't feel right. A document belongs only to one other item. Besides, I want to be able to extend the relations to more models if neccessary.
What you're looking for is called polymorphism. Basically, you're not associating a model with a fixed other model through a single other_model_id
field, but you keep track of two fields: other_model_class
and other_model_foreign_key
. That way you can associate a Document
with class: User, id: 42
in one case and class: Course, id: 42
in another. There's a Behavior in the Bakery, which should be a good place to start.
这篇关于CakePHP:属于多个人的模型,一次一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!