Laravel: Eloquent Sort By Relation

In Laravel 5.7, we have the Eloquent ORM to help with fetching data. However, sometimes we want to sort the data by a field in a related model and still retain the nested object structure of relations.

public function getPrograms(Request $request, $id) {

    $limit = $request->limit ?? 15;

    $programs = SchedulePrograms::where('schedule_id', $id)
                    ->with('program')
                    ->orderBy('long_name', 'asc') // throws error
                    ->paginate($limit);

    return Resource::collection($programs);
}

The above code throws an error because the field long_name is not present in the schedule_programs table but rather the programs table.

One way I have found to be able to achieve the correct sort order and still retain the nested structure is by

  1. joining to the related table and performing the order by
  2. then selecting the only fields from the parent table we are interested in
  3. and then using the with() function to pull the related models afterwards.
  4. Example below:

With those changes, the updated code now looks like the following:

public function getPrograms(Request $request, $id) {

    $limit = $request->limit ?? 15;

    $programs = SchedulePrograms::where('schedule_id', $id)
                    ->select('schedule_programs.*')
                    ->join('programs', 'programs.id', '=', 'schedule_programs.program_id')
                    ->orderBy('long_name', 'asc')
                    ->with('program') // gets the related data
                    ->paginate($limit);

    return Resource::collection($programs);
}

Quick and simple, and the same number of queries (2) are performed against the database, although slightly more expensive because of the join operation. However, if you have good indexing in place, this should not present any significant impact to your database.

Happy trails my good people, and Merry Christmas

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s