Home > Software engineering >  laravel - how to sort by different columns (first integer and then string)
laravel - how to sort by different columns (first integer and then string)

Time:08-11

I'm listing items ordered by device.sort_order integer column, which is working fine.

$parts = \App\DevicePart::with('device')->get()->sortBy('device.sort_order')->values();

@foreach($parts as $i)
  {{ $i->device->sort_order }} - {{ $i->title }}
@endforeach

This will produce a list like this:

1 - Carga
1 - Baseband
2 - Baseband
2 - Conectores
2 - Camera

So, now I want to secondly sort it by title field, without losing first order, so ITEM TITLES can be showed up alphabetically.

1 - Baseband
1 - Carga
2 - Baseband
2 - Camera
2 - Conectores

Is there any way to do this?

CodePudding user response:

Use ORDER BY sort_order, title, its equivalent in Laravel being:

$parts = \App\DevicePart::with('device')
    ->orderBy('sort_order')
    ->orderBy('title')
    ->get();
  • Related