我希望有一种简单且可重复使用的方式来与不同模型的特定表共享关系。我想要做的是指定一个表,使用外键列,如“parent_id”,然后将此表/模型与我的应用程序中的多个模型相关联。有没有办法在蛋糕中做到这一点,哪种方式最好?我想我需要在这个表中添加一个额外的列,以指定每行链接到的表,例如:
表1
id 0 1 2 name name0 name1 name2 ...
表2
id 0 1 2 name name0 name1 name2 ...
Common_table:
id 0 1 ... parent_id 0 0 parent_table表1表2
我希望上面的解释有意义,提前谢谢!
答案 0 :(得分:1)
是
创建关系时,您还可以设置条件
一个示例可能是一个应用程序,其中有许多可以注释的模型,因此它们都与Comment
模型处于hasMany关系。
您可以在评论表中创建一个列,其中包含正在评论的模型的名称以及存储该ID的parent_id
列。
所以评论表就像是
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
您可以在Post
模型中
public hasMany =array(
'Comment' => array(
'foreignKey' => 'parent_id',
'conditions' => array('Comment.model_name' => 'Post')
)
您可以在Receipt
模型中
public hasMany =array(
'Comment' => array(
'foreignKey' => 'parent_id',
'conditions' => array('Comment.model_name' => 'Receipt')
)
等等