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

时间:2015-01-16 21:57:35

标签: php laravel

我正在尝试动态地将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);
}

1 个答案:

答案 0 :(得分:10)

是的,您可以在创建查询对象后添加内容:

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