I have a model called Business(having columns description, name, view etc), it has a one to many relationship with the model "Rating". I want to query my Business model such that it returns a result that check if a search string is present in name or description and also sorts by the business having highest rating first then views the business has.
I have written a code for the search query. find below:
$business = Business::with('images')
->where('isActive', true)
->where(function ($q) use ($query) {
$q->where('name', 'LIKE', '%' . $query . '%')
->orWhere('description', 'LIKE', '%' . $query . '%');
})->get();
I know that I can fetch the average ratings of the business like this:
$averageRating = Rating::where('business_id', $id)->avg('rating');
$business = Business::with(['images'])->get();
foreach ($business as $item) {
$item["rating"] = floor($averageRating);
}
So, how do I order based on highest ratings first, then highest views