jedrzej / sortable
Laravel Eloquent 模型的可排序特性 - 使用请求参数对模型进行排序
0.0.12
2019-09-05 08:10 UTC
Requires
Requires (Dev)
Suggests
- jedrzej/searchable: Allows filtering your models using request parameters
- jedrzej/withable: Allows eager loading of relations using request parameters
README
此包为 Laravel 4/5/6 中的 Eloquent 模型添加排序功能。
您可能还会发现以下包很有用
- Searchable - 允许使用请求参数过滤模型
- Withable - 允许使用请求参数进行关系预加载
- Pimpable - 一个元包,结合了 Sortable、Searchable 和 Withable 行为
Composer 安装
将以下行添加到您的项目中的 composer.json
文件
"jedrzej/sortable": "0.0.12"
或在项目根目录的命令行中运行以下命令
composer require "jedrzej/sortable" "0.0.12"
设置可排序模型
为了使 Eloquent 模型可排序,将特性添加到模型中,并定义模型可以按其排序的字段列表。您可以定义一个 $sortable
属性,或者如果您想执行一些逻辑来定义可排序字段列表,可以实现 getSortableAttributes
方法。
use Jedrzej\Sortable\SortableTrait; class Post extends Eloquent { use SortableTrait; // either a property holding a list of sortable fields... public $sortable = ['title', 'forum_id', 'created_at']; // ...or a method that returns a list of sortable fields public function getSortableAttributes() { return ['title', 'forum_id', 'created_at']; } }
为了使所有字段可排序,在可排序字段列表中放置一个星号 *
public $sortable = ['*'];
排序模型
SortableTrait
为模型添加了一个 sorted()
范围 - 您可以传递一个数组形式的排序条件查询
// return all posts sorted by creation date in descending order Post::sorted('created_at,desc')->get(); // return all users sorted by level in ascending order and then by points indescending orders User::sorted(['level,asc', 'points,desc'])->get();
或者它将使用请求中的 sort
参数作为默认值
// return all posts sorted by creation date in descending order by appending to URL ?sort=created_at,desc //and then calling Post::sorted()->get(); // return all users sorted by level in ascending order and then by points indescending orders by appending to URL ?sort[]=level,asc&sort[]=points,desc // and then calling User::sorted()->get();
重写默认排序逻辑
通过在模型中实现名为 sortFieldName
的回调,可以重写如何使用和应用于查询的排序参数,例如。
// return all posts sorted by creation date in descending order Post::sorted('created_at,desc')->get(); // in model class overwrite the sorting logic so that 'created' field is used instead of 'created_at' public function sortCreatedAt($query, $direction = 'desc') { return $query->orderBy('created', $direction); }
定义默认排序标准
如果请求中没有提供排序标准,或者没有传递到模型中 sorted
方法的排序标准,可以定义默认排序标准。默认排序标准应定义在 $defaultSortCriteria 属性中,例如。
// sort by latest first protected $defaultSortCriteria = ['created_at,desc'];
定义默认排序顺序
默认情况下,asc 被认为是默认排序顺序。可以定义一个默认排序顺序,如果请求中没有提供排序顺序,或者没有传递到模型中 sorted
方法的排序顺序,将使用该默认排序顺序。默认排序顺序应定义在 $defaultSortOrder 属性中,例如。
// sort in desc order by default if no order is specified in request protected $defaultSortOrder = 'desc'; // sort in asc order by default if no order is specified in request protected $defaultSortOrder = 'asc';
其他配置
如果您正在使用 sort
请求参数进行其他目的,可以设置模型中的 $sortParameterName
属性来更改将被解释为排序标准的参数名称,例如。
protected $sortParameterName = 'sortBy';