0

This is my simple structure:

public class Post{
  public function user(){
     return $this->belongsTo(User::class);
  }
}

This is how I query (the query has pagination):

$query = Post::query();
$query->with('user');

I want to sort by user.name.
Now, I know that I can go $query->with('user',function(){...order by here});
But I need a detached method that I can run later in the stack.

$query->user->orderBy('name');
$query->user()->orderBy('name');

This https://stackoverflow.com/a/38741988/936651 says that it is possible, but I get the error: Undefined property/method: Illuminate\Database\Eloquent\Builder::$user

Is there any way to sort by related table after using with statement?

Thanks

Community
  • 1
  • 1
SexyMF
  • 10,657
  • 33
  • 102
  • 206

1 Answers1

0

Your code doesn't work because when you do $query = Post::query(); it will return an instance of the Query Builder, so when you after do $query->user() it gives you an error because the Query Builder does not have the method user(), that method exists in your Post model.

I won't provide any code since you've mentioned you already know how to do the with() way..

Saeed Prez
  • 728
  • 3
  • 8