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

查看:277
本文介绍了在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天全站免登陆