How to get count in relation table in yii2 Activerecord

I have a need to find the related data count from a Active Record,

I found a link from stackoverflow

There is a way mentioned in order to get the count of the related records




public function getComment_count()

{

    return Comment::find()->where(['post' => $this->id])->count();

}



I just want to know the best possible way to find out the count and using the above function would increase the load of queries on the database ?

For example I have




            EditorialLikesDislikes::find()

                ->where(['status' =>  EditorialLikesDislikes::STATUS_LIKE])                

                ->with( 'editorial.editorialLikes',

                        'editorial.editorialDislikes',                        

                        'editorialComments.user')

                ->groupBy('editorial_id')

                ->orderBy('count(editorial_id) DESC')

                ->asArray()

                ->all();



Now in relations i have


    /**

     * @return \yii\db\ActiveQuery

     */

    public function getEditorialDislikes()

    {

        return $this->hasMany(EditorialLikesDislikes::className(), ['editorial_id' => 'id'])

                ->where(['status' => EditorialLikesDislikes::STATUS_DISLIKE]);

    }


    /**

     * @return \yii\db\ActiveQuery

     */

    public function getEditorialLikes()

    {

        return $this->hasMany(EditorialLikesDislikes::className(), ['editorial_id' => 'id'])

                ->where(['status' => EditorialLikesDislikes::STATUS_LIKE]);

    }    



now i want only count the number of rows using the relation ‘editorial.editorialLikes’ mentioned above

Hi,





$results = EditorialLikesDislikes::find()

->where(['status' => EditorialLikesDislikes::STATUS_LIKE]) 

->with( 'editorial.editorialLikes',

'editorial.editorialDislikes', 

'editorialComments.user')

->groupBy('editorial_id')

->orderBy('count(editorial_id) DESC')

->asArray()

->all();

For example you have this code… you can access editorial.editorialDislikes as follows

count($results[’[size=“2”]editorial.editorialDislikes’[/size][size=“2”]]) … i hope this will give count [/size]

without heavy load :)