我正在使用CakePHP 3.x。
我想要的是能够调用$ this-&gt; Categories-&gt; find(),然后加入Topics.cat_id = Categories.id上的主题,然后加入Posts.topic_id = Topics.id上的帖子。< / p>
我没有收到任何错误,但我收到的唯一数据是类别数据,我尝试过LEFT和INNER加入但没有成功。任何帮助将不胜感激。
表关系是:
CategoriesTable
$this->hasMany('Topics');
TopicsTable
$this->belongsTo('Categories');
$this->hasMany('Posts');
PostsTable
$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'
]
]);
尝试使用可包含的行为,但现在我收到错误&#34;类别与帖子&#34;使用此查询:
$query = $this->Categories->find('all')
->order(['Categories.name' => 'ASC'])
->contain(['Topics', 'Posts' => function($q){
return $q->where(['Posts.topic_id' => 'Topics.id']);
}]);
答案 0 :(得分:19)
With the advice @ndm gave i was able to get the result i wanted. I must have overlooked the section in the docs, so anyone else having this problem, here's how to do it.
$query = $this->Categories->find('all')
->order(['Categories.name' => 'ASC'])
->contain([
'Topics.Posts.Users'
]);
答案 1 :(得分:3)
只要找到cakephp2的遗产,你仍然可以使用旧版本的连接。
$result = $this->Category->findAll(fields=>['id','Topic.id'], 'conditions'=>['Topic.name'=>'s'],'join'=>['Topic' => [
'table' => 'topics',
'type' => 'INNER',
'conditions' => 'Topic.category_id = Category.id'
]]);
找到熟悉的?你仍然可以像以前一样使用别名
第一次回答,不确定代码编辑器是如何工作的,抱歉。
答案 2 :(得分:-3)
试试这个:
$query = $this->Categories->find('all')
->fields('Categories.*', 'Topics.*', 'Posts.*')
->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'
]
]);
添加以下行:
->fields('Categories.*', 'Topics.*', 'Posts.*')
从主题和帖子中检索数据