如何在构建器中传递 3 个 orderBy 方法?

问题描述 投票:0回答:1

在 laravel 10 站点上,我有具有不同数量的排序字段的 sql 请求,例如:

    $sortByField = $request->sortBy ?? 'id';
    $orderBy = $request->orderBy ?? 'asc';
    $sortByField2 = 'id';
    $orderBy2 = 'asc';
    $sortByField3 = 'id';
    $orderBy3 = 'asc';

    if ($condition) {
        $sortByField = 'priority';
        $orderBy = 'desc';
        $sortByField2 = 'created_at';
        $orderBy2 = 'asc';
    }
   if ($condition2) {
        $sortByField = 'status';
        $orderBy = 'desc';
        $sortByField2 = 'priority';
        $orderBy2 = 'desc';
        $sortByField3 = 'created_at';
        $orderBy3 = 'asc';
    }
    $items = Item::search(search: $search)
        ->orderBy($sortByField, $orderBy)
        ->orderBy($sortByField2, $orderBy2)
        ->orderBy($sortByField3, $orderBy3)
        ->get();

orderBy的最大数量可以是3,所以我必须在上面写3个orderBy并使用默认值 在生成的 sql 中我有:

...
ORDER BY `priority` asc, `id` asc, `id` asc limit 20 offset 0

是否有办法让它变得更好?

提前致谢!

laravel eloquent
1个回答
0
投票

您可以根据您的条件动态添加

orderBy
子句来优化此功能。

$sortByField = $request->sortBy ?? 'id';
$orderBy = $request->orderBy ?? 'asc';

$query = Item::search($search)->orderBy($sortByField, $orderBy);

if ($condition) {
    $query->orderBy('priority', 'desc')->orderBy('created_at', 'asc');
}

if ($condition2) {
    $query->orderBy('status', 'desc')->orderBy('priority', 'desc')->orderBy('created_at', 'asc');
}

$items = $query->get();
© www.soinside.com 2019 - 2024. All rights reserved.