在 yii2 Activerecord 中获取关系表中的计数

2022-01-04 00:00:00 php yii2 yii 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();
}

只是传递...

相关文章