@gecko2811 you have three options to define the ordering:
Option 1. Callback Function with orderBy
// Controller:
Map::with(['routesExternal.runs' => function($query) {
$query->orderBy('runs.saves', 'desc');
}])->get();
Option 2. Model: ALWAYS Order By Field X
Maybe you want that relationship to always be ordered by that field?
You can do this:
app/Models/RouteExternal.php:
public function runs()
{
return $this->hasMany(Run::class, "way_id", "id")->orderBy('saves', 'desc');
}
Then, in the Controller, you just leave it as it was.
Option 3. Separate Ordered Relationship
If you want to use this ordering often but not always, another option is to create a separate relation function:
app/Models/RouteExternal.php:
public function runs()
{
return $this->hasMany(Run::class, "way_id", "id");
}
public function runsOrderedBySaves()
{
return $this->hasMany(Run::class, "way_id", "id")->orderBy('saves', 'desc');
// Or alternatively, even...
return $this->runs()->orderBy('saves', 'desc');
}
// Controller:
Map::with('routesExternal', 'routesExternal.runsOrderedBySaves')->get();
I've quickly created a post on my blog, as a reference to answer similar questions in the future.
Let me know if it works, and which way you've chosen :)