Laravel 来自动态数组输入的多个 orderBy

Laravel multiple orderBy from dynamic array input

我正在尝试将 orderBy 子句动态添加到查询中。

我试过的

$sort = Input::get('sort');

// Ex. of $sort below  
// Could be more or less key / values depending on user input
"category" => "asc",
"created_at" => "desc",
"email" => "asc",
"title" => "asc"

// I need to chain multiple orderBy's to a query
// but I can't use foreach in the laravel query
foreach ($sort as $key => $value) {
  echo "->orderBy(\"$key\", \"$value\")";
}

有没有办法将多个 orderBy 链接到现有查询?或者在创建查询期间将它们链接起来的方法?

我正在使用 Bootgrid 并尝试利用它的多重排序功能。

代码更新

这将生成状态代码 500。

$advertisements = DB::table('advertisements')
                    ->get();

foreach ($sort as $key => $value) {
    $advertisements->orderBy($key, $value);
}

是的,您可以在创建查询对象后向其添加内容,如下所示:

<?php
$query = DB::table('advertisements');
foreach (Input::get('sort') as $key => $value) {
    $query->orderBy($key, $value);
}
$advertisements = $query->get();