I have a thing class:
class Thing extends Eloquent
{
public function owner() {
return $this->belongsTo('Owner');
}
}
And an owner class:
class Owner extends Eloquent
{
public function things() {
return $this->hasMany('Thing');
}
}
I am getting a paginated list of Things ordered by some property of the thing like this:
Thing::orderBy('thing_property')->paginate(20);
But I realized I would like to get the list of things ordered by a property of their owners instead. Is there an Eloquent way to do this? I have tried a lot of different things with no success. I should probably include some things I've tried in my question, but there are a lot of them, most of them are probably dumb, and I can't really even get a good idea of whether any of them are even close. The most recent one was:
Thing::with('owner')->orderBy('owner.owner_property')->paginate(20);
After that not working and reading more about it, I see this is not how 'with()' should be used. Unfortunately, I have not been able to find anything about what I should be using instead.
You need to join owner's table. Eager loading (with
) doesn't join but runs another query for the related models.
$things = Thing::join('owners', 'owners.id', '=', 'things.owner_id')
->orderBy('owners.owner_property')
->get(['things.*']); // return only columns from things
Should you have any Thing
rows without Owner
(owner_id = null), use leftJoin
instead of join
.
It appears as though you have a good basic grasp on Laravels Eloquent ORM.
I would suggest the following if you wanted to get things
with the order based upon their parent owner
:
$results = Owner::with('things')
->orderBy('owner_property', 'ASC')
->paginate(20);
Or if you would like to order the parent owner
and then the children things
, you could do the following:
$results = Owner::with(array( 'things' =>
function($query){
$query->orderBy('things_property', 'DESC');
})
->orderBy('owner_property', 'ASC')
->paginate(20);