Vie*_*nto 5 cakephp associations has-many-through
我试图通过CakePHP中的关系来解决双向自我指导问题(多么令人满意!).
我正在开发一个图片匹配网站.
我首先定义了一个与连接模型的hasMany直通关系.
pictures_matches连接表具有以下结构:
id | picture_id | partner_id | rating | total_votes
Run Code Online (Sandbox Code Playgroud)
我的匹配连接模型关联看起来像这样:
class PictureMatch extends AppModel {
...
public $belongsTo = array(
'Picture' => array(
'className' => 'Picture',
'foreignKey' => 'picture_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Partner' => array(
'className' => 'Picture',
'foreignKey' => 'partner_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
Run Code Online (Sandbox Code Playgroud)
每张图片都需要能够从任一方向访问其相关图片,但这是我掌握的地方.看起来我需要保存关系的两边但是这会破坏存储在连接模型中的额外数据 - 有两个数据库条目,投票可能会因方向而异.
任何人都可以对CakePHP中最好的方法有所了解吗?我很困惑.
是否可以动态创建反向关系?
小智 0
您可以通过 Model::bindModel() 动态创建关系,这是非常有用的东西,这将允许您动态绑定反向关系或更确切地说任何您想要的方向。
http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html
另外,使用 Containable 行为,您可以创建无限链来检索关联的日期 ex。
包含('Picture.PictureMatch.Partner.PictureMatch.Picture......')
基本上,您可以循环遍历所有模型,只要每个链与下一个链以某种方式相关,以更好地解释它简单的示例(请忽略其中的逻辑)
圆属于正方形 正方形属于三角形
所以三角形与圆没有直接关系,但正方形介于两者之间
Circle->find('all', array('...', contain => array('Square.Triangle'));
Run Code Online (Sandbox Code Playgroud)
或者为了获得更多乐趣,让我们一圈一圈地循环
Circle->find('all', array('...', contain => array('Square.Trinagle.Square.Circle'));
Run Code Online (Sandbox Code Playgroud)
等等,当然这些例子是无用的,没有任何编程逻辑,但我希望你明白你可以通过无限数量的关系来回循环。