hichxm/laravel-sortable

Hichxm 为 Laravel 生态系统提供的 Laravel sortable 包

v1.0.2 2024-04-01 22:47 UTC

This package is auto-updated.

Last update: 2024-10-01 00:17:43 UTC


README

Laravel Sortable 是一个特性,可以为 Eloquent 模型添加可排序行为。

支持的 Laravel 版本

安装

您可以通过 composer 安装此包

composer require hichxm/laravel-sortable

使用方法

创建一个新的迁移来向您的表添加一个新列

Schema::table('addresses', function (Blueprint $table) {
    $table->orderColumn('order');
    
    // $table->dropOrderColumn('order'); // To drop the order column
});

Hichxm\LaravelSortable\HasSortableColumn 特性添加到您的模型中

use Hichxm\LaravelSortable\HasSortableColumn;

class Address extends Model
{
    use HasSortableColumn;
}

默认情况下,特性会寻找名为 order 的列,但您可以通过在模型中设置 $sortableColumn 属性来自定义此行为

class Address extends Model
{
    use HasSortableColumn;
    
    protected $sortableColumn = 'custom_order';
}

您现在可以在模型上使用以下方法来管理排序

$addressOne = Address::find(1);
$addressTwo = Address::find(2);
$addressThree = Address::find(3);

Address::swapOrder($addressOne, $addressTwo); // Swap the order of the two addresses
Address::setOrder($addressOne, 2); // Set the order of the address
Address::setNewOrder([$addressOne, $addressTwo, $addressThree]); // Set the order of the addresses

您还可以使用以下方法来获取查询排序结果

$addressQuery = Address::query();

$addressQuery->ordered()->get(); // Get the addresses ordered

$addressQuery->ordered('desc')->get(); // Get the addresses ordered in descending order
$addressQuery->orderedDesc()->get(); // Get the addresses ordered in ascending order

$addressQuery->ordered('asc')->get(); // Get the addresses ordered in ascending order
$addressQuery->orderedAsc()->get(); // Get the addresses ordered in ascending order

测试

vendor/bin/phpunit

许可

MIT 许可证 (MIT)。有关更多信息,请参阅许可文件