Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 我可以用Elounting命令孩子们按照他们父母的财产进行收集吗?_Php_Laravel 4_Eloquent - Fatal编程技术网

Php 我可以用Elounting命令孩子们按照他们父母的财产进行收集吗?

Php 我可以用Elounting命令孩子们按照他们父母的财产进行收集吗?,php,laravel-4,eloquent,Php,Laravel 4,Eloquent,我有一门课: class Thing extends Eloquent { public function owner() { return $this->belongsTo('Owner'); } } 和一个所有者类: class Owner extends Eloquent { public function things() { return $this->hasMany('Thing'); } } 我得到了一

我有一门课:

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()”应该如何使用的。不幸的是,我还没有找到任何关于我应该使用什么的信息。

看来你对Laravels雄辩的ORM有很好的基本掌握

如果您想根据父项
所有者
订购
物品,我建议如下:

$results = Owner::with('things')
    ->orderBy('owner_property', 'ASC')
    ->paginate(20);
或者,如果您想订购父
所有者
,然后订购子
物品
,您可以执行以下操作:

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

您需要加入所有者的表。即时加载(
with
)不会加入,但会对相关模型运行另一个查询

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

如果您有任何
Thing
行没有
Owner
(Owner\u id=null),请使用
leftJoin
而不是
join

@ThomasAndrews,我的解决方案将返回一个所有者集合,其中还包含一个您可以迭代的things属性。然而,正如deczo所指出的,Laravel通过执行两个查询来实现这一点——他的解决方案更整洁,并且完全符合您的要求:)