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.
You can do this using joins (and eager loading data if needed)
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?
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
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!
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...
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community