Lines:
1 - Data coming from the filter form
2 - This with I enter into a Model relationship function. I do this because I need to sort my list in order of the MEDIA column. Home
3 - The strange thing is that I need to do an INNER JOIN for the same table, because otherwise some columns I want to get in QUERY do not work. This I do not understand in Laravel. Yes, I am the one who is wrong, but I do not know where. Home
4 - Within this JOIN I look for dealers that have ratings and do not have, as I choose in the filters form, so I do this IF . Home
5 - Then I do the AVG (RATING) to bring the average rating that the dealership has. Home
6 - The function ORDER_AVG and CLOSURE are in MODEL . Home
7 - In the filters form there is the option of the user to choose the records that have a certain average (1 to 5). That's why I'm using HAVING . But it does not work, it does not filter. I do not understand why either.
$arrData = Input::all();
$consulta = Dealer::with(['order_avg'])
->join('dealer_ratings', function($q) use ($arrData){
if(array_key_exists('filterByAvaliacao', $arrData)){
if($arrData['filterByAvaliacao'] == 1)
$q->on('dealer_ratings.id_concessionaria', '=', 'dealers.id');
else
$q->on('dealer_ratings.id_concessionaria', '<>', 'dealers.id');
}
else
$q->on('dealer_ratings.id_concessionaria', '<>', 'dealers.id');
$q->whereNotIn('id_status', [1, 4]);
})
->selectRaw('*, dealers.id, count(dealer_ratings.id) as qtd_avaliacoes, AVG(rating) as media')
->groupBy('dealers.id')
->orderBy('media', 'desc')
->whereIdCidade($arrData['filterByCidade'])
->whereIdTipo($arrData['filterByTipo'])
->closure(function($query) use ($arrData){
if($arrData['filterByMarca'] && $arrData['filterByMarca'] != 0){
$query->whereIdMarca($arrData['filterByMarca']);
}
if($arrData['palavras-chaves'] != ''){
$query->where('concessionaria', 'REGEXP', $arrData['palavras-chaves']);
}
})
->paginate(10);
MODEL
public function scopeClosure($query, \Closure $callback) {
$callback($query);
return $query;
}
# Order By Media de Stars
public function order_avg(){
return $this->hasMany('App\DealerRating', 'id_concessionaria')
->selectRaw('AVG(rating) as media')
->having('media', '=', Input::get('filterByStars'));
}
Summary:
I want to get a dealer list conditioned by City and Brand. And in the same query bring the average rating and ordered by it.