M
M
Maxim Grechushnikov2015-03-31 18:53:18
Yii
Maxim Grechushnikov, 2015-03-31 18:53:18

Yii2: How to sort by number of records through cross table?

In continuation of the Yii2 topic: How to make hasMany through a cross table and count all records?
It would be necessary somehow now to sort all this by members_count ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Korovin, 2015-03-31
@maxyc_webber

At me so:
Model Service - services. They connect to clients through the clients_services (ServiceViaUser) table, and the Client model.
In ServiceSearch:

public function search($params)
    {
        $query = Service::find();

        $query->joinWith(['clients']);

        $query->groupBy(['products_services.id']);

        $query->select([Service::tableName().'.*', 'COUNT('.ServiceViaUser::tableName().'.id) as num_clients']);

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $dataProvider->sort->attributes['num_clients']=[
            'asc' => ['num_clients' => SORT_ASC],
            'desc' => ['num_clients' => SORT_DESC],
        ];

I think this code is enough for understanding, if not, unsubscribe, I will give more detailed examples.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question