Order by
You can also sort your query results using a column from another table using the orderByPowerJoins method.
User::orderByPowerJoins('profile.city');
If you need to pass some raw values for the order by function, you can do like this:
User::orderByPowerJoins(['profile', DB::raw('concat(city, ", ", state)')]);
This query will sort the results based on the city column on the user_profiles table. You can also sort your results by aggregations (COUNT, SUM, AVG, MIN or MAX).
For instance, to sort users with the highest number of posts, you can do this:
$users = User::orderByPowerJoinsCount('posts.id', 'desc')->get();
Or, to get the list of posts where the comments contain the highest average of votes.
$posts = Post::orderByPowerJoinsAvg('comments.votes', 'desc')->get();
You also have methods for SUM, MIN and MAX:
Post::orderByPowerJoinsSum('comments.votes');
Post::orderByPowerJoinsMin('comments.votes');
Post::orderByPowerJoinsMax('comments.votes');
In case you want to use left joins in sorting, you also can:
Post::orderByLeftPowerJoinsCount('comments.votes');
Post::orderByLeftPowerJoinsAvg('comments.votes');
Post::orderByLeftPowerJoinsSum('comments.votes');
Post::orderByLeftPowerJoinsMin('comments.votes');
Post::orderByLeftPowerJoinsMax('comments.votes');