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

时间:2014-11-12 19:30:03

标签: php activerecord yii yii2

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

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

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

但我不知道如何在Yii2中实现这一点来计算用户的帖子:find():用(' ...')在gridview中显示。
有没有人在yii2中试试这个?

2 个答案:

答案 0 :(得分:8)

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

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

只是传递它......

答案 1 :(得分:3)

您可以尝试以下代码:

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();

请注意,postsUser模型中定义的关系,如下所示:

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