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]);
}
答案 0 :(得分:2)
orderBy(字符串$列,字符串$ 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