CakePHP:属于多个人的模型,一次一个 [英] CakePHP: Model that belongs to multiple others, one at a time

查看:218
本文介绍了CakePHP:属于多个人的模型,一次一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个表:用户,课程和文档。我想将文档上传到用户以及课程,所以我需要两个文档模型的属性关系。有些属于一个模型,有些属于另一个模型。



是否有一个简单的解决方案来构建这些关系?



如何设置添加动作?



我知道我可以设置两个连接表并使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆