简体   繁体   English

来自不同模型的同一个表的多个关系

[英]Multiple relations to same table from different models

I would like to have a simple and reusable way of sharing a relations with a specific table with different models. 我希望有一种简单且可重用的方式来与具有不同模型的特定表共享关系。 What I would like to do is the possibility to specify a table, with a foreign key column such as "parent_id" and then associate this table/model to several models in my app. 我想做的是指定一个带有外键列(例如“ parent_id”)的表,然后将此表/模型与我的应用程序中的多个模型相关联。 Is there a way to do this in cake, and which is the best way? 有没有办法做到这一点,那是最好的方法? I guess I would need an additional column in this table, to specify which is the table every row is linked to, eg: 我想我需要在此表中增加一列,以指定每行链接到的表,例如:

Table1 表格1

id 0 1 2 name name0 name1 name2 ... id 0 1 2名称name0 name1 name2 ...

Table2 表2

id 0 1 2 name name0 name1 name2 ... id 0 1 2名称name0 name1 name2 ...

Common_table: Common_table:

id 0 1 ... parent_id 0 0 parent_table Table1 Table2 id 0 1 ... parent_id 0 0 parent_table表1表2

I hope the explanation above made sense, thanks in advance! 我希望上面的解释有意义,在此先感谢!

yes

when you create a relationship you can also set the conditions 创建关系时,您还可以设置条件

An example could be an application in which you have many models that can be commented, so they all are in a hasMany relationship with Comment Model. 例如,在一个应用程序中,您有许多可以注释的模型,因此它们都与Comment Model处于hasMany关系中。

You can create a column in comments table storing the name of the model being commented and a parent_id column storing the id. 您可以在注释表中创建一列,以存储要注释的模型的名称,并在parent_id列中存储ID。

So the comments table would tipically be something like 所以注释表通常是这样的

id | parent_id | model_name | comment_text         | user_id
---+-----------+------------+----------------------+-------
1  | 15        | Post       | I like this Post     | 3
1  | 15        | Post       | I like this Post too | 5
2  | 19        | Receipt    | This receipt is good | 3

in your Post Model you can do 在您的Post模型中,您可以执行

public hasMany =array(
    'Comment' => array(
        'foreignKey' => 'parent_id',
        'conditions' => array('Comment.model_name' => 'Post')
    )

in your Receipt Model you can do 在您的Receipt模型中,您可以执行

public hasMany =array(
    'Comment' => array(
        'foreignKey' => 'parent_id',
        'conditions' => array('Comment.model_name' => 'Receipt')
    )

and so on 等等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM