M
M
Mokhirjon Naimov2016-04-22 08:40:05
Laravel
Mokhirjon Naimov, 2016-04-22 08:40:05

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,
]);

It is necessary that when the page of popular channels is opened (ie $request->sort == 'popular') the elements are sorted by the amount of votes.
The fact is that the voting data is in a separate table, and after the case 'popular' there is a conflict with the general conditions (and the rest of the cases work correctly):
$items = $items->whereStatus('active')
    ->with('category', 'attributes')
    ->paginate(12);

How to make case 'popular' work correctly and not interfere with general conditions and cases?
PS Error messages:

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

1 answer(s)
M
Mokhirjon Naimov, 2016-05-03
@zvermafia

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 question

Ask a Question

731 491 924 answers to any question