Wis*_*d0m 17 php mysql cakephp join cakephp-3.0
我正在使用CakePHP 3.x.
我想要的是能够调用$ this-> Categories-> find()然后加入Topics.cat_id = Categories.id上的主题,然后加入Posts.topic_id = Topics.id上的帖子.
我没有得到任何错误,但我收到的唯一数据是类别数据,我尝试过LEFT和INNER加入但没有成功.任何帮助将不胜感激.
表关系是:
CategoriesTable
$this->hasMany('Topics');
Run Code Online (Sandbox Code Playgroud)
TopicsTable
$this->belongsTo('Categories');
$this->hasMany('Posts');
Run Code Online (Sandbox Code Playgroud)
PostsTable
$this->belongsTo('Topics');
Run Code Online (Sandbox Code Playgroud)
还有我的查询:
$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'
]
]);
Run Code Online (Sandbox Code Playgroud)
尝试使用可包含的行为但现在我使用此查询得到错误"类别与帖子无关":
$query = $this->Categories->find('all')
->order(['Categories.name' => 'ASC'])
->contain(['Topics', 'Posts' => function($q){
return $q->where(['Posts.topic_id' => 'Topics.id']);
}]);
Run Code Online (Sandbox Code Playgroud)
Wis*_*d0m 20
根据@ndm给出的建议,我能够得到我想要的结果.我一定忽略了文档中的部分,所以其他人都有这个问题,这里是如何做到的.
$query = $this->Categories->find('all')
->order(['Categories.name' => 'ASC'])
->contain([
'Topics.Posts.Users'
]);
Run Code Online (Sandbox Code Playgroud)