I have no clue why you wanted to order Post
s based on their User
's created_at
field. Perhaps, a different angle to the problem is needed - like accessing the Post
from User
instead.
That being said, an orderBy()
can accept a closure as parameter which will create a subquery then, you can pair it with whereRaw()
to somewhat circumvent Eloquent and QueryBuilder limitation*.
Post::orderBy(function($q) {
return $q->from('users')
->whereRaw('`users`.id = `posts`.id')
->select('created_at');
})
->get();
It should generate the following query:
select *
from `posts`
order by (
select `created_at`
from `users`
where `users`.id = `posts`.id
) asc
A join might serve you better, but there are many ways to build queries.
*As far as I know, the subquery can't be made to be aware of the parent query fields