I know from laravel documentation that I can do eager loading like:
$records = (new Route)->with('country')->get();
But when I execute this:
$records = (new Route)->query()->with('country')->orderBy('country.name', 'asc')->paginate();
I get this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'country.name' in 'order clause' (SQL: select * from `routes` order by `country`.`name` asc limit 2 offset 0)
How I can sort on related model ? How can I force laravel to load joined tables?
I find the solution:
$records = (new Route)->query()->join('countries', 'routes.country_id', '=', 'countries.id');
But is not ideal because joining are performed manualy.
You can do the following with eager loading :
$records = (new Route)->with(['country' => function ($q) {
$q->orderBy('name', 'asc');
}])->get(); // or paginate or whatever