如何在CakePhp中建立三元关系? [英] How to Model Ternary Relationship in CakePhp?
问题描述
页表
(1)
|
|
(*)
User_Moderate_Page(*)-----------(1)Access_level表
(*)
|
|
(1)
用户表
Page table
(1)
|
|
(*)
User_Moderate_Page (*)----------- (1)Access_level table
(*)
|
|
(1)
User table
如何在CakePhp中建立这样的三元关系?
用户到页面可以使用hasBelongtoMany关系建模。但是User_Moderate_page只是一个关联表,我是否应该在Cake中为User_Moderate_Page编写一个模型?
How do i Model such a ternary relationship in CakePhp? User to Page can be modelled using the hasBelongtoMany Relationship. But User_Moderate_page is just an association table, should I even write a Model for User_Moderate_Page in Cake?
推荐答案
它与通用表:
假设你有3个表 - 第一,秒,第三 - 每个都有主键'id'。
Let me generalize it by describing it with generic tables: Lets say you have 3 tables - firsts, seconds, thirds - each with primary keys 'id'.
让你的连接表每个主表使用外键调用firsts_seconds_thirds:
let your join table be called 'firsts_seconds_thirds' with foreign keys to each main table:
- first_id
- second_id
- third_id
- <此关联表的其他字段>
- first_id
- second_id
- third_id
- <additional fields of this association table>
通常我们定义表之间的HABTM关系,在这种情况下,我们需要为连接表创建一个蛋糕模型 - 让它叫 FirstsSecondsThird (通过cakePhp的命名约定)
usually we define HABTM relationships between tables, in this case we need to create a cake model for the join table - lets call it FirstsSecondsThird (By cakePhp's naming conventions)
您需要定义的模型之间的关系是:
The relationship between models you need to define is:
- 首先 hasMany FirstsSecondsThird
- 第二有多少 FirstsSecondsThird
- 第三有多少 FirstsSecondsThird
- FirstsSecondsThird belongsTo 第一,第二,第三
- First hasMany FirstsSecondsThird
- Second hasMany FirstsSecondsThird
- Third hasMany FirstsSecondsThird
- FirstsSecondsThird belongsTo First,Second,Third
a href =http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasmany-through =nofollow>一起链接模型
同样的代码:
The need for this is explained here - Associations: Linking Models Together
Code for the same:
class First extends AppModel {
public $hasMany = array(
'FirstsSecondsThird' => array(
'className' => 'FirstsSecondsThird',
'foreignKey' => 'first_id'
)
);
}
//Same for classes 'Second' and 'Third'
class FirstsSecondsThird extends AppModel {
public $belongsTo = array(
'First' => array(
'className' => 'First',
'foreignKey' => 'first_id'
),
'Second' => array(
'className' => 'Second',
'foreignKey' => 'second_id'
),
'Third' => array(
'className' => 'Third',
'foreignKey' => 'third_id'
)
);
}
这些模型是完全设置,但现在插入/更新/ / join表应该正确或者没有用。
Model :: saveMany()
和 Model :: saveAssociated()
等等需要使用。阅读它此处。
您还需要考虑这些连接表的ON DELETE RESTRICT / CASCADE,并对它们进行适当的建模。
The models are perfectly setup, but now inserting/updating/deleting from the main/join table should be done correctly or they are of no use.
Model::saveMany()
and Model::saveAssociated()
, using the option 'deep' etc. need to be used. Read about it here.
You also need to think about ON DELETE RESTRICT/CASCADE for these join tables and model them appropriately.
这篇关于如何在CakePhp中建立三元关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!