05-09-2022

Order by Relationship column, Solved it!

This was a thousand year old tricky question for me. But no more!

To order a query by a relationship column, you need a few things:

Use the following:

$posts = Post::query()
  ->withAggregate('user', 'name')
  ->orderBy('user_name')
  ->get();

What happens? Give the following:

->withAggregate('RELATIONSHIP', 'COLUMN')

So you can use the RELATIONSHIP_COLUMN as an addition to your original query.

Original inspiration: https://laravel-code.tips/use-the-withaggregate-method-to-add-related-values-to-eloquent-queries-using-subselects/


© 2022 PappZ. All rights reserved.