0

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?

anderlaini
  • 1,593
  • 2
  • 24
  • 39
  • Can you show what the data looks like? It's not clear, and the answer you've accepted appears incorrect based on the code you've provided. Show the output from `dump(DevicePart::with('device')->get())` – miken32 Aug 10 '22 at 17:31

1 Answers1

3

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

$parts = \App\DevicePart::with('device')
    ->orderBy('sort_order')
    ->orderBy('title')
    ->get();
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • 1
    1 catch (deleted my comment), looks like `sort_order` is on the `devices` table, so you'd need a join in there to be able to sort it by that column. – Tim Lewis Aug 10 '22 at 15:05
  • @TimLewis Laravel is not my main area of expertise. Maybe you can answer? Great first name, BTW. – Tim Biegeleisen Aug 10 '22 at 15:14
  • 1
    Thanks fellow Tim! I would have to guess, since I don't know the relationship between `DevicePart` and `Device` (I'd assume `device_parts.device_id`?), but yeah; `::with('device')` is a sub-query, not a join, so `orderBy('sort_order')` would currently be an unknown column error. `->join('devices', 'device_parts.device_id', '=', 'devices.id')` ([Docs](https://laravel.com/docs/9.x/queries#joins)). But yeah; your answer is correct, once joined – Tim Lewis Aug 10 '22 at 15:18