如何使用 CakePHP 3 连接多个表?

How to join multiple tables using CakePHP 3?

我正在使用 CakePHP 3.x。

我想要的是能够调用 $this->Categories->find() 然后在 Topics.cat_id = Categories.id 上加入主题,然后在 Posts.topic_id 上加入帖子= Topics.id.

我没有收到任何错误,但我得到的唯一数据是类别数据,我尝试了 LEFT 和 INNER 连接但没有成功。任何帮助将不胜感激。

table 关系是:

类别表

$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'
            ]
        ]);

尝试使用可包含的行为,但现在我在使用此查询时收到错误 "Categories is not associated with Posts":

$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'
        ]);

试试这个:

 $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.*')

从主题和帖子中检索数据

只要找到那种cakephp2的遗留问题,你仍然可以像旧版本一样使用join。

$result = $this->Category->findAll(fields=>['id','Topic.id'], 'conditions'=>['Topic.name'=>'s'],'join'=>['Topic' => [
            'table' => 'topics',
            'type' => 'INNER',
            'conditions' => 'Topic.category_id = Category.id'
        ]]);

觉得眼熟?您仍然可以像以前一样使用别名

第一次回答,不知道代码编辑器是如何工作的,抱歉。