来自动态数组输入的 Laravel 多个 orderBy
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27993441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel multiple orderBy from dynamic array input
提问by Rafael
I am trying to add orderBy clauses to a query dynamically.
我正在尝试将 orderBy 子句动态添加到查询中。
What I've tried
我试过的
$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\")";
}
Is there a way to chain multiple orderBy's to an existing query? Or a way to chain them during the creation of the query?
有没有办法将多个 orderBy 链接到现有查询?或者在创建查询期间链接它们的方法?
I am using Bootgridand trying to utilize it's multisort capabilities.
我正在使用Bootgrid并尝试利用它的多重排序功能。
Code update
代码更新
This is producing a status code 500.
这会产生状态代码 500。
$advertisements = DB::table('advertisements')
->get();
foreach ($sort as $key => $value) {
$advertisements->orderBy($key, $value);
}
回答by mopo922
Yes, you can add stuff to your query object after creating it like this:
是的,您可以像这样创建后向查询对象添加内容:
<?php
$query = DB::table('advertisements');
foreach (Input::get('sort') as $key => $value) {
$query->orderBy($key, $value);
}
$advertisements = $query->get();