Answer the question
In order to leave comments, you need to log in
How to make a proper query for sorting in Laravel?
There is this code:
$items = $this->channels;
// Category
if ($request->has('category'))
{
$items = $items->where('category_id', $request->category);
}
// Sort by default (count_subscribers, DESC)
if ($request->has('sort'))
{
switch ($request->sort)
{
case 'popular':
$items = $items->votes()
->select(DB::raw('SUM(value) as vote_total'))
->orderBy('vote_total', 'DESC');
break;
case 'new':
$items = $items->latest();
break;
default:
$items = $items->orderBy('count_subscribers', 'DESC');
break;
}
}
else
{
$items = $items->orderBy('count_subscribers', 'DESC');
}
$items = $items->whereStatus('active')
->with('category', 'attributes')
->paginate(12);
return view('frontend/channels/all', [
'items' => $items,
]);
$items = $items->whereStatus('active')
->with('category', 'attributes')
->paginate(12);
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'status' in 'where clause' (SQL: select count(*) as aggregate from `votes` where `votes`.`voteable_id` is null and `votes`.` voteable_id` is not null and `votes`.`voteable_type` = App\Models\Channel and `status` = active)
Answer the question
In order to leave comments, you need to log in
In short, I did this (but I didn’t want to do this), when creating a new record (or update / delete) in the `votes` table, I immediately read the sum of the votes for the App\Models\Channel model and do an update in the `channels.vote_total` table (then available for the Channel model). And change the 'popular' case to the code below:$items = $items->orderBy('vote_total', 'DESC');
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question