hippieua/laravel-sortable

用于Laravel模型排序的Trait

1.0.1 2022-07-04 08:45 UTC

This package is auto-updated.

Last update: 2024-09-09 01:09:59 UTC


README

Latest Version on Packagist Total Downloads

此包允许您使用简单的方法对Laravel模型记录的排序顺序进行排序

$model->moveUp();
$model->moveDown();
$model->move('up');
$model->move('down');

安装

要安装最新版本,请运行以下命令。

composer require hippieua/laravel-sortable

设置

您的模型应包含可排序字段。您可以添加新的或使用现有的一个(不要使用默认的id字段)

Schema::table('comments', function (Blueprint $table) {
    $table->unsignedInteger('order')->default(1);
});

更新您的模型,使用Sortable trait并填充$sortable_field属性,根据您添加的字段名称。

    use Hippie\Sortable\Sortable;
    
    class Comment extends Model
    {
        use Sortable;
        
        protected string $sortable_field = 'order';
        
        protected $fillable = [
            'order',
        ];
    }

如果您的模型有BelongsTo关系,并且您想在关系项中上下移动记录,则填充$sortable_relation属性。

use Hippie\Sortable\Sortable;

class Comment extends Model
{
    use Sortable;
    
    protected string $sortable_field = 'order';
    protected string $sortable_relation = 'post';
    
    protected $fillable = [
        'order',
    ];
    
    public function post(): BelongsTo
    {
        return $this->belongsTo(Post::class);
    }
class Post extends Model
{
    public function comments(): BelongsTo
    {
        return $this->hasMany(Comment::class)->orderBy('order'); 
    }    
}

如果您不想在创建新项时手动计算可排序字段值,请将static::created添加到您的可排序模型中

protected static function booted()
{
    static::created(function ($model) {
        $model->updateSortOrderOnCreate();
    });
}

用法

添加新项

$comment = $post->comments()->create([
    'text' => $request->text,
])

$comment->order的值将被设置为$post->comments->count() + 1

排序现有项

$post->comments()->first()->moveDown()

将第一个评论的order字段值设置为2,并将第二个项的order字段值设置为1;

可用方法

$comment->moveUp();
$comment->moveDown();
$comment->move('up');
$comment->move('down');

信息

在Laravel 8和9版本上进行测试

致谢

许可

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