Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get count in relation table in yii2 Activerecord

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').....

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?

like image 781
Araz Jafaripur Avatar asked Nov 12 '14 19:11

Araz Jafaripur


1 Answers

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

Just a passing it along...

like image 123
brdflp Avatar answered Sep 30 '22 20:09

brdflp