Laravel 5.4 排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41999357/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:14:52  来源:igfitidea点击:

Laravel 5.4 sorting

phpmysqlsqllaravellaravel-5.4

提问by Virgil de Meijer

I've got 2 columns, Model and Action. First thing I would like to achieve is to order the model from A to Z.

我有 2 列,模型和操作。我想实现的第一件事是从 A 到 Z 订购模型。

I'm doing that with

我正在这样做

orderBy('model', 'ASC')

Then I would like to order the action column on index, create, store etc. I've got a query, and i'me trying to sort the results in order: index, create, store, show, edit, update, destroy, [everything else].

然后我想对索引、创建、存储等操作列进行排序。我有一个查询,我正在尝试按顺序对结果进行排序:索引、创建、存储、显示、编辑、更新、销毁, [其他一切]。

However the result i'm getting is: [everything else], index, create, store, show, edit, update, destroy

然而,我得到的结果是:[所有其他]、索引、创建、存储、显示、编辑、更新、销毁

Query:

询问:

Permission::orderBy('model', 'ASC')->orderByRaw("FIELD(action, 'index', 'create', 'store', 'show', 'edit', 'update', 'destroy')")->get();

Result should be something like:

结果应该是这样的:

  • model 1, index
  • model 1, create
  • model 1, store
  • etc
  • model 1, everything else
  • model 2, index
  • model 2, create
  • model 2, store
  • etc
  • model 2, everything else
  • 模型 1,索引
  • 模型1,创建
  • 模型 1, 商店
  • 等等
  • 模型 1,其他一切
  • 模型 2,索引
  • 模型2,创建
  • 模型 2, 商店
  • 等等
  • 模型 2,其他一切

Has anyone got an idea how I can fix this?

有没有人知道我该如何解决这个问题?

Thanks

谢谢

回答by Mayank Pandeyz

The orderBymethod allows you to sort the result of the query by a given column. The first argument to the orderBy method should be the column you wish to sort by, while the second argument controls the direction of the sort and may be either ascor desc, check the example:

orderBy方法允许您按给定列对查询结果进行排序。orderBy 方法的第一个参数应该是您希望排序的列,而第二个参数控制排序的方向,可以是ascor desc,请查看示例:

$users = DB::table('table')
->orderBy('name', 'desc')  // You can pass as many columns as you required
->get();