spatie/eloquent-sortable
Composer 安装命令:
composer require spatie/eloquent-sortable
包简介
Sortable behaviour for eloquent models
README 文档
README
Sortable behaviour for Eloquent models
This package provides a trait that adds sortable behaviour to an Eloquent model.
The value of the order column of a new record of a model is determined by the maximum value of the order column of all records of that model + 1.
The package also provides a query scope to fetch all the records in the right order.
Spatie is a webdesign agency in Antwerp, Belgium. You'll find an overview of all our open source projects on our website.
Support us
Learn how to create a package like this one, by watching our premium video course:
We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.
We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.
Installation
For Laravel 6.x or PHP 7.x, use version 3.x of this package.
This package can be installed through Composer.
composer require spatie/eloquent-sortable
In Laravel 5.5 and above the service provider will automatically get registered. In older versions of the framework just add the service provider in config/app.php file:
'providers' => [ ... Spatie\EloquentSortable\EloquentSortableServiceProvider::class, ];
Optionally you can publish the config file with:
php artisan vendor:publish --tag=eloquent-sortable-config
This is the content of the file that will be published in config/eloquent-sortable.php
return [ /* * The name of the column that will be used to sort models. */ 'order_column_name' => 'order_column', /* * Define if the models should sort when creating. When true, the package * will automatically assign the highest order number to a new model */ 'sort_when_creating' => true, /* * Define if the timestamps should be ignored when sorting. * When true, updated_at will not be updated when using setNewOrder */ 'ignore_timestamps' => false, ];
Usage
To add sortable behaviour to your model you must:
- Implement the
Spatie\EloquentSortable\Sortableinterface. - Use the trait
Spatie\EloquentSortable\SortableTrait. - Optionally specify which column will be used as the order column. The default is
order_column.
Example
use Spatie\EloquentSortable\Sortable; use Spatie\EloquentSortable\SortableTrait; class MyModel extends Model implements Sortable { use SortableTrait; public $sortable = [ 'order_column_name' => 'order_column', 'sort_when_creating' => true, ]; // ... }
If you don't set a value $sortable['order_column_name'] the package will assume that your order column name will be named order_column.
If you don't set a value $sortable['sort_when_creating'] the package will automatically assign the highest order number to a new model;
Assuming that the db-table for MyModel is empty:
$myModel = new MyModel(); $myModel->save(); // order_column for this record will be set to 1 $myModel = new MyModel(); $myModel->save(); // order_column for this record will be set to 2 $myModel = new MyModel(); $myModel->save(); // order_column for this record will be set to 3 //the trait also provides the ordered query scope $orderedRecords = MyModel::ordered()->get();
You can set a new order for all the records using the setNewOrder-method
/** * the record for model id 3 will have order_column value 1 * the record for model id 1 will have order_column value 2 * the record for model id 2 will have order_column value 3 */ MyModel::setNewOrder([3,1,2]);
Optionally you can pass the starting order number as the second argument.
/** * the record for model id 3 will have order_column value 11 * the record for model id 1 will have order_column value 12 * the record for model id 2 will have order_column value 13 */ MyModel::setNewOrder([3,1,2], 10);
You can modify the query that will be executed by passing a closure as the fourth argument.
/** * the record for model id 3 will have order_column value 11 * the record for model id 1 will have order_column value 12 * the record for model id 2 will have order_column value 13 */ MyModel::setNewOrder([3,1,2], 10, null, function($query) { $query->withoutGlobalScope(new ActiveScope); });
To sort using a column other than the primary key, use the setNewOrderByCustomColumn-method.
/** * the record for model uuid '7a051131-d387-4276-bfda-e7c376099715' will have order_column value 1 * the record for model uuid '40324562-c7ca-4c69-8018-aff81bff8c95' will have order_column value 2 * the record for model uuid '5dc4d0f4-0c88-43a4-b293-7c7902a3cfd1' will have order_column value 3 */ MyModel::setNewOrderByCustomColumn('uuid', [ '7a051131-d387-4276-bfda-e7c376099715', '40324562-c7ca-4c69-8018-aff81bff8c95', '5dc4d0f4-0c88-43a4-b293-7c7902a3cfd1' ]);
As with setNewOrder, setNewOrderByCustomColumn will also accept an optional starting order argument.
/** * the record for model uuid '7a051131-d387-4276-bfda-e7c376099715' will have order_column value 10 * the record for model uuid '40324562-c7ca-4c69-8018-aff81bff8c95' will have order_column value 11 * the record for model uuid '5dc4d0f4-0c88-43a4-b293-7c7902a3cfd1' will have order_column value 12 */ MyModel::setNewOrderByCustomColumn('uuid', [ '7a051131-d387-4276-bfda-e7c376099715', '40324562-c7ca-4c69-8018-aff81bff8c95', '5dc4d0f4-0c88-43a4-b293-7c7902a3cfd1' ], 10);
You can also move a model up or down with these methods:
$myModel->moveOrderDown(); $myModel->moveOrderUp();
You can also move a model to the first or last position:
$myModel->moveToStart(); $myModel->moveToEnd();
You can determine whether an element is first or last in order:
$myModel->isFirstInOrder(); $myModel->isLastInOrder();
You can swap the order of two models:
MyModel::swapOrder($myModel, $anotherModel);
Grouping
If your model/table has a grouping field (usually a foreign key): id, user_id, title, order_column
and you'd like the above methods to take it into considerations, you can create a buildSortQuery method at your model:
// MyModel.php public function buildSortQuery() { return static::query()->where('user_id', $this->user_id); }
This will restrict the calculations to fields value of the model instance.
Dispatched events
Once a sort has been completed, an event (Spatie\EloquentSortable\EloquentModelSortedEvent) is dispatched that you
can listen for. This can be useful for running post-sorting logic such as clearing caches or other actions that
need to be taken after a sort.
The event has an isFor helper which allows you to conveniently check the Eloquent class that has been sorted.
Below is an example of how you can listen for this event:
use Spatie\EloquentSortable\EloquentModelSortedEvent as SortEvent; class SortingListener { public function handle(SortEvent $event): void { if ($event->isFor(MyClass::class)) { // ToDo: flush our cache } } }
Tests
The package contains some integration/smoke tests, set up with Orchestra. The tests can be run via phpunit.
vendor/bin/phpunit
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
Alternatives
License
The MIT License (MIT). Please see License File for more information.
spatie/eloquent-sortable 适用场景与选型建议
spatie/eloquent-sortable 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 25.39M 次下载、GitHub Stars 达 1.51k, 最近一次更新时间为 2014 年 07 月 15 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「sortable」 「model」 「sort」 「laravel」 「eloquent」 「behaviour」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 spatie/eloquent-sortable 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 spatie/eloquent-sortable 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 spatie/eloquent-sortable 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table.
Syntactic sugar for PHP's sorting
Easily provide front-end sorting controls for SilverStripe lists
Plug-ins for DataTables
A package for automatically encrypting and decrypting Eloquent attributes in Laravel 5.5+, based on configuration settings.
Interfaces for web resource models and services to retrieve and create them
统计信息
- 总下载量: 25.39M
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1525
- 点击次数: 23
- 依赖项目数: 326
- 推荐数: 145
其他信息
- 授权协议: MIT
- 更新时间: 2014-07-15