leparking/laravel-sortable

Laravel 包,用于排序 Eloquent 模型

0.2.0 2016-05-14 16:03 UTC

This package is not auto-updated.

Last update: 2024-09-14 18:47:43 UTC


README

A Laravel 5.2 package to sort Eloquent models.

Build Status

安装

使用 composer 安装此包

composer require leparking/laravel-sortable

将服务提供者添加到 config/app.php

    'providers' => [
        // ...
        LeParking\Sortable\SortableServiceProvider::class,
    ],

配置

发布默认配置文件到 config/sortable.php

php artisan vendor:publish

此文件中的设置将应用于所有可排序模型,但可以用每个模型的 $sortable 属性覆盖。

以下是可用的设置及其默认值

return [
     // Name of the column that will store the position.
    'column' => 'position',

     // If set to true, new models will be inserted at the first position.
    'insert_first' => false,

     // A column name or an array of columns names to group sortable models.
    'group_by' => false,
];

使用

您的可排序模型应实现 Sortable 接口并使用 SortableTrait

use Illuminate\Database\Eloquent\Model;
use LeParking\Sortable\Sortable;
use LeParking\Sortable\SortableTrait;

class Book extends Model implements Sortable
{
    use SortableTrait;

    // Optional property to override default settings.
    protected $sortable = [
        // ...
    ];
}

数据库表必须有一个整数列来存储位置。

Schema::create('books', function($table) {
    $table->integer('position')->unsigned();
});

在创建新模型时,将自动填充 position 属性。

$book = Book::create();
echo $book->position; // 1

$book2 = Book::create();
echo $book2->position; // 2

SortableTrait 提供了一个查询范围,用于按位置列检索模型。

$books = Book::ordered();
$books = Book::ordered('desc');

类似包