Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

I am dealing with similar problem. I am afraid that it cannot be done with Eloquent, but I hope I am wrong. Any help will be highly appreciated.

Last updated 2 years ago.
0

You can do this using joins (and eager loading data if needed)

Last updated 2 years ago.
0

Yes but join breaks the nice JSON structure of nested data :( Or can data using joins be somehow formatted in a way that eloquent does?

Last updated 2 years ago.
0

TorchSK said:

Yes but join breaks the nice JSON structure of nested data :( Or can data using joins be somehow formatted in a way that eloquent does?

You don't have to select joined columns so it really doesn't matter. Imagine this:

Post::join('categories','posts.category_id','=','categories.id')
  ->orderBy('categories.name', 'asc')
  // with('category') if we need to get related categories, uncomment
  ->get(['posts.*']); // get only post table, so the result is just the same
Last updated 2 years ago.
0

jarektkaczyk said:

TorchSK said:

Yes but join breaks the nice JSON structure of nested data :( Or can data using joins be somehow formatted in a way that eloquent does?

You don't have to select joined columns so it really doesn't matter. Imagine this:

Post::join('categories','posts.category_id','=','categories.id')
 ->orderBy('categories.name', 'asc')
 // with('category') if we need to get related categories, uncomment
 ->get(['posts.*']); // get only post table, so the result is just the same

Wow, this is brilliant! Thanks a lot!

Last updated 2 years ago.
0

You could also use the sort collection method:

$collection->sort(function($a, $b) {
  $fa = $a->related_obj->field;
  $fb = $b->related_obj->field;
  if ($fa === $fb) return 0;
  return ($fa > $fb) ? 1 : -1;
});

It's the most "elegant" way I found without using query builder...

Last updated 9 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

spescina spescina Joined 14 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.