【问题标题】:Laravel OrderBy Errors with 5.8 UpgradeLaravel OrderBy 5.8 升级错误
【发布时间】:2020-05-10 03:10:54
【问题描述】:

在 Laravel 5.8 中遇到问题,因为 orderBy 命令停止工作。我将如何重写控制器的这两个区域以使其停止抛出错误?


public function index(Request $request)
{
    $clients = Client::orderBy('identifier', 'name')->paginate(15);
    return view('admin.clients.index')->with('clients', $clients);
}

public function closed()
{
    $sortBy = 'name';
    $query = Client::onlyTrashed()->orderBy($sortBy, $sortBy == 'created_at' ? 'name' : 'asc')
        ->orderBy('created_at', 'name');
    $projects = $query->get();
    return view('admin.clients.index')->with(['clients' => $projects, 'sortBy' => $sortBy]);
}

【问题讨论】:

  • 如果您确实包含了提到的错误会很有帮助

标签: laravel laravel-5.8


【解决方案1】:

orderBy(string $column, string $direction = 'asc')

orderBy有两个参数,第二个是方向。 在5.8版本之前,如果你传递的方向值不是asc,它会自动将desc设置为方向值:

$this->{$this->unions ? 'unionOrders' : 'orders'}[] = [
            'column' => $column,
            'direction' => strtolower($direction) == 'asc' ? 'asc' : 'desc',
        ];

Laravel 5.8+之后,如果方向值不是asc或者desc,会报错:

if (! in_array($direction, ['asc', 'desc'], true)) {
            throw new InvalidArgumentException('Order direction must be "asc" or "desc".');
        }

所以如果你想按两列排序,你可以使用两个orderBy

$clients = Client::orderBy('identifier')->orderBy('name')->paginate(15);

# Raw SQL:
# select * from clients order by identifier asc, name asc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-24
    • 2020-10-10
    • 2020-12-07
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多