如何在 Laravel 5.5 中通过急切加载关系进行排序?

Muh*_*bas 5 relationship laravel eloquent laravel-5

下面的代码运行完美,并以 JSON 格式显示我的 API 的所有折扣产品。但我想要折扣表中按 id 排序的结果。就像是orderBy('discount.id', 'desc')。任何人都可以为此提供解决方案吗?如何将 orderBy 与表id中的列一起使用?discounthas()

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

Ale*_*ris 2

您可以在语句中使用函数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");
}
Run Code Online (Sandbox Code Playgroud)

您可以在文档中阅读有关此内容的内容。