gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-29 00:00:46 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com