【发布时间】:2015-08-05 11:34:42
【问题描述】:
我正在使用 CakePHP 3.x。
我想要的是能够调用 $this->Categories->find() 然后加入 Topics.cat_id = Categories.id 上的主题,然后加入 Posts.topic_id = Topics.id 上的帖子。
我没有收到任何错误,但我得到的唯一数据是类别数据,我尝试了 LEFT 和 INNER 连接但没有成功。任何帮助将不胜感激。
表关系为:
分类表
$this->hasMany('Topics');
主题表
$this->belongsTo('Categories');
$this->hasMany('Posts');
帖子表
$this->belongsTo('Topics');
还有我的查询:
$query = $this->Categories->find('all')
->order(['Categories.name' => 'ASC'])
->join([
'topics' => [
'table' => 'Topics',
'type' => 'LEFT',
'conditions' => 'topics.Cat_id = Categories.id'
],
'posts' => [
'table' => 'Posts',
'type' => 'LEFT',
'conditions' => 'posts.topic_id = topics.id'
]
]);
尝试使用可包含的行为,但现在我使用此查询收到错误“类别与帖子不关联”:
$query = $this->Categories->find('all')
->order(['Categories.name' => 'ASC'])
->contain(['Topics', 'Posts' => function($q){
return $q->where(['Posts.topic_id' => 'Topics.id']);
}]);
【问题讨论】:
-
您正在寻找包含,而不是手动连接。 book.cakephp.org/3.0/en/orm/…
-
@ndm 感谢您的回复。我已经用包含的结果更新了我的问题,有什么建议吗?
-
仔细看看如何定义嵌套关联。
标签: php mysql cakephp join cakephp-3.0