dongmu9253 2015-01-16 21:57
浏览 898
已采纳

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

I am trying to add orderBy clauses to a query dynamically.

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?

I am using Bootgrid and trying to utilize it's multisort capabilities.

Code update

This is producing a status code 500.

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

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

1条回答 默认 最新

  • douju8113 2015-01-16 22:00
    关注

    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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图