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

查看:17
本文介绍了计入包含 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

这不会返回关联星星的数量.

This does not return the number of associated Stars.

有什么不对的地方还是应该以其他方式解决?

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

谢谢

推荐答案

你还必须选择外键,否则蛋糕无法加入表格.而且你还必须对结果进行分组

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天全站免登陆