Answer the question
In order to leave comments, you need to log in
How to do Relation Count with eager loading?
In the first yii, everything was done quite simply, but in the second, a plug that leads to 250 requests on a normal page. And I would like to do everything without crutches.
there is relation:
public function getPostStatisticsCount()
{
return $this->hasMany(PostStatistics::className(), ['post_id' => 'id'])->count();
}
$mm = Post::find()->with('postStatisticsCount')... ->all();
Answer the question
In order to leave comments, you need to log in
$customers = Customer::find()
->select([
'{{customer}}.*', // select all customer fields
'COUNT({{order}}.id) AS ordersCount' // calculate orders count
])
->joinWith('orders') // ensure table junction
->groupBy('{{customer}}.id') // group the result to ensure aggregation function works
->all();
I pulled it out from the sources ... PostStatistics
and group byPost
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question