我可以用Eloquent命令一个集合的孩子的父母的属性


Can I use Eloquent to order a collection of children by a property of their parents?

我有一个东西类:

class Thing extends Eloquent
{
    public function owner() {
        return $this->belongsTo('Owner');
    }
}

和一个所有者类:

class Owner extends Eloquent
{
    public function things() {
        return $this->hasMany('Thing');
    }
}

我得到的是一个按属性排序的事物的分页列表,就像这样:

Thing::orderBy('thing_property')->paginate(20);

但是我意识到我想要的是按物品所有者的属性排序的物品列表。是否有一种雄辩的方式来做到这一点?我尝试了很多不同的东西,但都没有成功。我应该在我的问题中加入一些我尝试过的东西,但有很多,其中大多数可能是愚蠢的,我甚至不能很好地知道其中是否有任何一个接近。最近的一条是:

Thing::with('owner')->orderBy('owner.owner_property')->paginate(20);

在不工作和阅读更多关于它之后,我看到这不是'with()'应该如何使用。不幸的是,我没有找到任何关于我应该使用的东西。

您需要加入所有者的表。急切加载(with)不加入,而是对相关模型运行另一个查询。

$things = Thing::join('owners', 'owners.id', '=', 'things.owner_id')
              ->orderBy('owners.owner_property')
              ->get(['things.*']); // return only columns from things

如果您有任何Thing行没有Owner (owner_id = null),使用leftJoin代替join

看来你已经很好地掌握了Laravels Eloquent ORM。

如果你想获得things和基于它们的父owner的订单,我建议如下:

$results = Owner::with('things')
    ->orderBy('owner_property', 'ASC')
    ->paginate(20);

或者,如果您想要订购父owner,然后订购子things,您可以执行以下操作:

$results = Owner::with(array( 'things' => 
    function($query){
        $query->orderBy('things_property', 'DESC');
    })
    ->orderBy('owner_property', 'ASC')
    ->paginate(20);