计数包含Cakephp 3 [英] Count in contain Cakephp 3

查看:45
本文介绍了计数包含Cakephp 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张桌子发布,它与星级桌子有很多关联。

I have a table Post and this has a has-many association with a table Stars.

我可以使用以下方式获取所有关联数据:

I can get all the associated data using:

$this->Posts->find()->contain(['Stars']);

效果很好。

但是我想数星星。我已经尝试过了,但是它不起作用:

But I want to count the Stars. I have tried this but its not working:

$this->Posts->find->contain([
    'Stars' => function($q) {
        return $q->select(['total' => $q->func()->count('Stars.post_id')]);
    }
]);

//I've also tried this
...
...$q->select(['total' => "COUNT(Stars.post_id)"]);
...
//Also fail

此操作不返回数字

是不是有问题或应该以其他方式处理?

Is there something wrong or should do it some other way?

谢谢

推荐答案

您还必须选择外键,否则Cake无法加入表。而且您还必须将结果分组

you have to select also the foreign key otherwise cake is not able to join the tables. And you have also to group the result

'Stars' => function($q) {
    $q->select([
         'Stars.post_id',
         'total' => $q->func()->count('Stars.post_id')
    ])
    ->group(['Stars.post_id']);

    return $q;
}

这篇关于计数包含Cakephp 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆