如何通过Laravel 5.5中的“急货”关系订购?

如何通过Laravel 5.5中的“急货”关系订购?,laravel,eloquent,relationship,laravel-5.5,Laravel,Eloquent,Relationship,Laravel 5.5,下面的代码可以完美地工作,并以JSON格式为my API显示所有折扣产品 public function promotions() { return $this->prepareResult(true, Product::has('discount')->where(['company_id'=> 1, 'is_active'=>1])->with('category')->with('discount')->get(), [],"All Promoti

下面的代码可以完美地工作,并以JSON格式为my API显示所有折扣产品

public function promotions()
{
return $this->prepareResult(true, Product::has('discount')->where(['company_id'=> 1, 'is_active'=>1])->with('category')->with('discount')->get(), [],"All Promotions");
}

但我希望结果按折扣表中的id排序。类似于orderBy('discount.id','desc')。任何人都可以提供解决方案!如何使用has()在“折扣”表中使用带有“id”列的orderBy?

您可以使用
with
语句中的函数:

public function promotions()
{
    return $this->prepareResult(true, Product::has('discount')
        ->where(['company_id'=> 1, 'is_active'=>1])
        ->with('category')
        ->with(['discount' => function ($query) {
            return $query->orderBy('id','DESC');
        }])->get(), [],"All Promotions");
}

您可以在文档中了解这一点。

如果您想选择收集方法路线而不是Alex的答案(这也是有效的),您可以在获取后继续链接收集方法。由于包含了with(),因此可以执行以下操作

->get()->sortBy('discount.id')

与您的问题无关,但想指出,您可以将多个参数传递给with(),这样就不会调用它两次

Product::has('discount')->where(['company_id'=> 1, 'is_active'=>1])->with('discount', 'category')->get()

让我直截了当地说-您想按
折扣.id
订购产品吗?你需要使用join。你想要基于折扣的产品列表订单吗?我正在寻找DESC订单,我已经尝试过这种方法。我仍然没有按降序获得ID!!!:-(您是否将
orderby
更改为DESC?这将对
折扣进行排序,而不是对
产品进行排序。使用sortByDesc()方法尝试了您的方法,但仍然没有得到递减id。如果您将('Product::has('discount')->where(['company_id'=>1,'is_-active'=>1])->与('discounter','category')->get()->sortByDesc('discounter.id'))->Pull('discount.id')->toArray())显示了什么?