简体   繁体   English

Laravel在查询中动态排序依据

[英]Laravel Dynamic Order By in Query

I have a table with 10 different fields. 我有一个包含10个不同字段的表格。 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. 因此,当我访问/inventory/sort/quantity ,应该按数量生成订单。

Instead, I get a strtolower() error. 相反,我收到一个strtolower()错误。

Any ideas on how to accomplish this? 关于如何做到这一点的任何想法?

Looks like there is a bit of recursion here. 看起来这里有点递归。 Running a query inside of a orderBy. 在orderBy内部运行查询。

I would return the conditioning into the orderBy method. 我将把条件返回到orderBy方法中。

 if($sortBy == 'desired condition') 
    { $sortBy = 'desired condition'; $dir == "asc/..."; } 
 ...orderBy($sortBy, $dir)...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM