在 yii2 Activerecord 中获取关系表中的计数 [英] get count in relation table in yii2 Activerecord

查看:23
本文介绍了在 yii2 Activerecord 中获取关系表中的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表用于帖子和用户.我想在用户列表 gridview 中显示用户的帖子计数.在 yii 1 中,我在模型中使用它来为此目的定义一个关系:

I have two table for post and user. I want to show post count of user in users list gridview. In yii 1 I use this in model to define a relation for this purpose:

'postCount' => array(self::STAT, 'Post', 'author',
            'condition' => 'status = ' . Post::ACTIVE),

...
User:find...().with('postCount').....

但我不知道如何在 Yii2 中实现它以获取 User:find():with('...') 中的帖子数以显示在 gridview 中.
有人在 yii2 中尝试过吗?

But i don't know how to implement this in Yii2 to get count of post in User:find():with('...') to show in gridview.
Anyone try this in yii2?

推荐答案

这是我所做的一个示例,到目前为止它似乎工作正常.它用于获取对帖子的评论计数.我只是使用了一个标准的活动记录计数,并使用 $this->id 和条目的主键创建了与 where 语句的关系,它得到了计数.

Here is an example of what I did and it seems to work fine so far. It was used to get a count of comments on a post. I simply used a standard active record count and created the relation with the where statement using $this->id and the primary key of the entry its getting a count for.

public function getComment_count()
{
    return Comment::find()->where(['post' => $this->id])->count();
}

只是传递...

这篇关于在 yii2 Activerecord 中获取关系表中的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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