根据排序 ID 订购产品

时间:2021-07-26 19:17:09

标签: laravel eloquent

我有一个表单,它根据我在 postman 中插入的 sortId 返回产品,一切正常,但 orderby 不适用于所有这些。

    $products = Product::with('raffles')
    ->whereHas('categories',function($q2) use ($categoryId) {
        $q2->where('category_id', $categoryId);
    })
    ->where(function ($query) use ($sortId) {
        //Default order
        if ($sortId == 1) {
            $query->orderBy('id');
        } 
        //Has raffle
        if ($sortId == 2) {
            $query->whereHas('raffles',function($q2) {
                $q2->where('active', 1);
            })->orderBy('created_at', 'desc');
        } 
        //More sold tickets
        if ($sortId == 3) {

            $query->whereHas('raffles',function($q2) {
                $q2->where('active', 1)
                    ->orderBy('sold_ticket', 'asc');
            });
        } 
    })
   ->paginate(10);

1 个答案:

答案 0 :(得分:1)

在你的代码中

$query->whereHas('raffles',function($q2) {
    $q2->where('active', 1)
    ->orderBy('sold_ticket', 'asc');
});

应该

$query->whereHas('raffles',function($q2) {
    $q2->where('active', 1);
})
->orderBy('sold_ticket', 'asc');

也许如果您使用 when() 方法重写查询?

$products = Product::with('raffles')
    ->whereHas('categories',function ($q2) use ($categoryId) {
        $q2->where('category_id', $categoryId);
    })
    ->when($sortId == 1, function ($query) {
        $query->orderBy('id');
    })
    ->when($sortId == 2, function ($query) {
        $query->whereHas('raffles', function ($q2) {
                $q2->where('active', 1);
            })
            ->orderBy('created_at', 'desc');
    })
    ->when($sortId == 3, function ($query) {
        $query->whereHas('raffles', function ($q2) {
                $q2->where('active', 1);
            })
            // sort the relationship column
            ->with([
                'raffles' => function ($q2) {
                    $q2->orderBy('sold_ticket', 'asc');
                }
            ]);
    })
   ->paginate(10);

如果 $sortId'1''2''3',这应该有效。如果 $sortId 是 像 '1,2,3' 这样的字符串或数组,你需要做一些不同的事情。

$sortId = explode(',' $sortId); // ['1', '2', '3']

并且在条件中,而不是$sortId == 1,执行in_array('1', $sortId)

相关问题