Answer the question
In order to leave comments, you need to log in
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
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],
];
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question