D
D
Dmitry Bay2015-08-27 13:31:54
Yii
Dmitry Bay, 2015-08-27 13:31:54

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

There is a function call with eager loading
$mm =  Post::find()->with('postStatisticsCount')... ->all();

But eager loading doesn't work.
Similar behavior is described here - https://github.com/yiisoft/yii2/issues/2179 .
On the yii forum, I was advised to push the relation into the class constructor.
I would like an example of a solution with a constructor.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita, 2015-08-27
@bitver

$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 ...
Something like this works in my application, although if possible, it is better to go from the opposite and search through the model PostStatisticsand group byPost

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question