获取yii2 Activerecord中关系表中的count


get count in relation table in yii2 Activerecord

我有两个表用于post和user。我想在用户列表网格视图中显示用户的帖子计数。在yii 1中,我使用这个In模型来定义一个用于此目的的关系:

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

但我不知道如何在Yii2中实现这一点,以在User:find()中获得帖子数:在gridview中显示("…")
有人在yii2上试试这个吗?

下面是我所做的一个例子,到目前为止它似乎运行良好。它被用来统计帖子上的评论数。我只使用了一个标准的活动记录计数,并使用$this->id和条目的主键创建了与where语句的关系。

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

只是路过。。。

您可以尝试以下代码:

User::find()->joinWith('posts',true,'RIGHT JOIN')->where(['user.id'=>'posts.id'])->count();

或者,如果您想指定用户计数:

//user id 2 for example
User::find()->joinWith('posts',true,'RIGHT JOIN')->where(['user.id'=>'posts.id','user.id'=>2])->count();

请注意,posts是在您的User模型中定义的关系,如下所示:

public function getPosts()
{
    return $this->hasMany(Post::className(), ['user_id' => 'id']);
}

我仍然认为,对于那些可能关心的人来说,如果你只是想让计数成为一个选择,而不是数据,那么最好使用这个来代替imho:

$count = (new 'yii'db'Query())
->select('count(*)')
->from('table')
->where(['condition'=>'value'])
->scalar();
echo $count;