php 在 yii2 Activerecord 中获取关系表中的计数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26894987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get count in relation table in yii2 Activerecord
提问by Araz Jafaripur
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:
我有两个表用于帖子和用户。我想在用户列表 gridview 中显示用户的帖子数。在 yii 1 中,我在模型中使用它来为此目的定义一个关系:
'postCount' => array(self::STAT, 'Post', 'author',
'condition' => 'status = ' . Post::ACTIVE),
...
User:find...().with('postCount').....
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?
但我不知道如何在 Yii2 中实现它以获取 User:find():with('...') 中的帖子数以显示在 gridview 中。
有人在 yii2 中尝试过吗?
回答by brdflp
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.
这是我所做的一个例子,到目前为止它似乎工作正常。它用于获取对帖子的评论计数。我只是使用了一个标准的活动记录计数,并使用 $this->id 和条目的主键创建了与 where 语句的关系,它得到了计数。
public function getComment_count()
{
return Comment::find()->where(['post' => $this->id])->count();
}
Just a passing it along...
只是传递而已...
回答by Ali MasudianPour
You can try the code below:
你可以试试下面的代码:
User::find()->joinWith('posts',true,'RIGHT JOIN')->where(['user.id'=>'posts.id'])->count();
Or if you want to specify a user count:
或者,如果您想指定用户数:
//user id 2 for example
User::find()->joinWith('posts',true,'RIGHT JOIN')->where(['user.id'=>'posts.id','user.id'=>2])->count();
Please note that, posts
is a relation defined in your User
model like below:
请注意,posts
是您的User
模型中定义的关系,如下所示:
public function getPosts()
{
return $this->hasMany(Post::className(), ['user_id' => 'id']);
}
回答by Bruno de Oliveira
Well still I think for those who it may concern, if you JUST want the count a select and not the data it will be better use this instead imho:
好吧,我仍然认为对于那些可能关心的人来说,如果你只是想要一个选择而不是数据,那么最好使用它而不是 imho:
$count = (new \yii\db\Query())
->select('count(*)')
->from('table')
->where(['condition'=>'value'])
->scalar();
echo $count;