Sorting by a Relationship in Eloquent

Here is an example of an Eloquent query that eager loads albums and artists and sorts the results by columns in the relationships.

$tracks = Track::join('albums', 'tracks.album_id', '=', 'albums.id')
  ->join('artists', 'albums.artist_id', '=', 'artists.id')
  ->with(['album', 'album.artist'])
  ->orderBy('artists.name')
  ->orderBy('albums.title', 'DESC')
  ->limit(200)
  ->get(['*', 'tracks.id', 'tracks.name']);

In order to sort by the related artist name, we need to use a join like we did with the query builder. However, doing a join results in some of the tracks column values getting overwritten. Specifically, tracks.id gets overwritten by the id column of the last joined table (artists.id). tracks.name gets overwritten by artists.name. In order to fix this, we can specify what we want as the id and name for tracks in the get method. In the code above, all columns are selected via the *, just like SELECT * in SQL, and then the columns that got overwritten by the joins are reset via tracks.id and tracks.name.