drf16571 2017-10-03 20:15
浏览 239
已采纳

在查询中的Laravel动态排序

I have a table with 10 different fields. I want to be able to click the column of the table then the page will reload with the order by in the column that was selected.

I've added this to my routes:

Route::get('/inventory/sort/{sortby}', ['uses' => 'ItemController@index']); 

My Controller:

 public function index($sortby = null) {
    $Inventory_Items = ItemDynamic::with(['Item'])
                     ->orderBy(function ($query) use($sortby) {
                         if ($sortby == "quantity") {
                           $query->orderBy('Quantity','asc');
                         } else if ($sortby == 'name') {
                           $query->orderBy('name','asc');
                         } else {
                           $query->orderBy('id','asc');
                         }
                       })
                     ->paginate(20);
        return view('adminlte::Item.index', ['Inventory_Items' => $Inventory_Items]);
    }

So, when I access /inventory/sort/quantity it should result in a order by quantity.

Instead, I get a strtolower() error.

Any ideas on how to accomplish this?

  • 写回答

1条回答 默认 最新

  • dongziya9863 2017-10-03 20:23
    关注

    Looks like there is a bit of recursion here. Running a query inside of a orderBy.

    I would return the conditioning into the orderBy method.

     if($sortBy == 'desired condition') 
        { $sortBy = 'desired condition'; $dir == "asc/..."; } 
     ...orderBy($sortBy, $dir)...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?