繁体   English   中英

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

[英]get count in relation table in yii2 Activerecord

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

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

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

但是我不知道如何在Yii2中实现这个来获取用户的帖子数:find():with('...')在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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM