I want to do a related query, but the ordering must be done by a field from another table that is in the relationship.
$consulta = Dealer::whereIdMarca($codMarca)
->whereIdCidade($codCidade)
->get();
Relationship
public function order_avg_rating(){
return $this->hasMany("App\DealerRating", "id_concessionaria")
->selectRaw('AVG(rating) as media')
->groupBy('id_concessionaria');
}
Sorting would be for establishments that have more stars and more ratings . Do not order! Also, if I make a direct JOIN on Dealer :: on the Controller, lose all relationships I did in Model for other things ...
"/
I'm trying other things:
Inquiry
$consulta = Dealer::whereIdMarca($codMarca)
->whereIdCidade($codCidade)
->where('concessionaria', 'like', '%'.$consultaCon.'%')
->with('order_avg')
->get()
->sortByDesc('order_avg.media, order_avg.qtd_avaliacoes')
->reverse();
I'm trying to sort by average and number of ratings. But it does not apply what I'm doing. I do not know what happens that does not order. It automatically sorts through the registration order, possibly.
Model
public function order_avg(){
return $this->belongsToMany('App\Dealer', 'dealer_ratings', 'id_concessionaria', 'id_concessionaria')
->withPivot('id_concessionaria')
->selectRaw('count(dealer_ratings.id) as qtd_avaliacoes, AVG(rating) as media')
->groupBy('dealers.id');
}