我正在使用 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']);
}]);
最佳答案
根据@ndm 的建议,我得到了我想要的结果。我一定是忽略了文档中的部分,所以任何遇到此问题的人,都可以按照以下方法解决。
$query = $this->Categories->find('all')
->order(['Categories.name' => 'ASC'])
->contain([
'Topics.Posts.Users'
]);
关于php - 如何使用 CakePHP 3 连接多个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30413740/