'Eager loading relationships to sort by is not working in Laravel
I am trying to use Eager Loading to dynamically order by relationships in Laravel.
dd(SomeModel::with(['someRelation' => function ($query) {
$query->orderByDesc('column');
})->toSql());
I'm using dd() and toSql() to try to debug what is happening and this is what I see:
"select * from "some_table" where "some_table"."deleted_at" is null"
No matter if I orderBy('column', 'ASC') or orderBy('column', 'DESC') without the dd or toSql, I get the same output as if it is ignoring the entire eager load.
Am I missing something or doing something wrong? My relation in this case looks like this:
class SomeModel
{
protected $table = 'some_table'; # for visual aid
public function someRelation(): BelongsTo
{
$this->belongsTo(SomeOtherModel::class)->select('id', 'column');
}
}
FYI, some more debug later. I attempted to try see if the function ever executes, to which it does:
SomeModel::with(['someRelation' => function ($query) {
$query->orderByDesc('column');
dd($query->toSql());
});
The dd block executes telling me the function executed and gives me:
"select "id", "name" from "some_other_table" where "some_other_table"."id" in (?, ?) and "some_other_table"."deleted_at" is null order by "name" desc"
Any help appreciated.
Update to check for subqueries SQL:
\DB::enableQueryLog();
SomeModel::with(['someRelation' => function ($test) {
$test->orderBy('name', 'DESC');
}])->get();
dd(\DB::getQueryLog());
This returns me an empty array:
[]
Solution 1:[1]
After reading through the full article as @TimLewis alluded to, I went with the join solution.
SomeModel::query()->select('some_table.id', 'some_table.name') # Only bring back what we need without the join
->join('some_other_table', 'some_other_table.id', '=', 'some_table.some_other_table_id')
->orderByDesc('column');
Alternatively, you can always leftJoin if you don't expect data all the time, just make some null exception handling.
I actually created an abstract class which has a global scope to do this dynamically in any Model based on a hash-map approach.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jaquarh |
