lartisan/laravel-sortable-medialibrary

将文件与Eloquent模型关联并添加可排序行为

9.4.2 2021-01-15 07:55 UTC

This package is auto-updated.

Last update: 2024-09-16 01:11:10 UTC


README

Total Downloads Latest Stable Version License

对原始包的更改

此分支包从 Spatie\MediaLibrary\MediaCollections\Models\Media 中删除了 IsSorted 特性,因此可以通过 spatie/eloquent-sortable 来实现排序/排序部分。我还添加了 spatie/eloquent-sortable 作为依赖项。

安装

此包使用 "spatie/eloquent-sortable": "^3.11""spatie/laravel-medialibrary": "^9.0.0" 一起,可以通过Composer安装

composer require lartisan/laravel-sortable-medialibrary

在Laravel 5.5及以上版本中,服务提供程序将自动注册。在框架的较旧版本中,只需将服务提供程序添加到 config/app.php 文件中即可

'providers' => [
    ...
    Spatie\MediaLibrary\MediaLibraryServiceProvider::class,
    Spatie\EloquentSortable\EloquentSortableServiceProvider::class,
];

可选地,您可以使用以下命令发布配置文件

php artisan vendor:publish --provider="Spatie\MediaLibrary\MediaLibraryServiceProvider" --tag="migrations"
php artisan vendor:publish --provider="Spatie\EloquentSortable\EloquentSortableServiceProvider" --tag="config"

用法

要将预期的Eloquent可排序行为添加到自定义Media模型中,您必须

  1. 实现 Spatie\EloquentSortable\Sortable 接口。
  2. 使用特质 Spatie\EloquentSortable\SortableTrait
  3. 可选地,指定将用作排序列的列。默认为 order_column
  4. 可选地,如果您的模型/表有一个分组字段,您可以在模型中创建一个 buildSortQuery 方法。

示例

...
use Spatie\EloquentSortable\Sortable;
use Spatie\EloquentSortable\SortableTrait;
use Spatie\MediaLibrary\MediaCollections\Models\Media as BaseMedia;

class MyCustomMedia extends BaseMedia implements Sortable
{
    use SortableTrait;
    
    /**
     * Define the column used for sorting
     * @var array
     */
    public $sortable = [
        'order_column_name' => 'order_column',
        'sort_when_creating' => true,
    ];

    /**
     * @return Builder
     */
    public function buildSortQuery(): Builder
    {
        return static::query()
            ->where('collection_name', $this->collection_name);
    }
    ...
}

要将原始包的默认排序行为添加到自定义Media模型中

您仍然可以通过向模型添加 Spatie\MediaLibrary\MediaCollections\Models\Concerns\IsSorted 来使用原始包的默认 IsSorted 行为。

示例

...
use Spatie\MediaLibrary\MediaCollections\Models\Concerns\IsSorted;
use Spatie\MediaLibrary\MediaCollections\Models\Media as BaseMedia;

class MyCustomMedia extends BaseMedia
{
    use IsSorted;
}

文档

原始的 spatie/laravel-medialibrary 包。

spatie/eloquent-sortable 包。

许可

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