cape-and-bay/versionable

Laravel 模型草稿工具

v1.0.1 2023-01-18 17:10 UTC

This package is auto-updated.

Last update: 2024-09-18 20:54:28 UTC


README

⏱️ 使 Laravel 模型支持版本控制。

这是一种使模型支持版本历史记录的极简方式,并且可以非常简单地回滚到指定的版本。

要求

  1. PHP >= 8.1
  2. laravel/framework >= 9.0

安装

composer require cape-and-bay/versionable -vvv

然后运行以下命令创建数据库迁移

php artisan migrate

用法

CapeAndBay\Versionable\Versionable 特性添加到您想要版本化的模型中

use CapeAndBay\Versionable\Versionable;

class Post extends Model
{
    use Versionable;

    # Prevents versioning Post if only the "is_active" column is updated.
    protected array $dont_version = ['is_active'];
}

在保存可版本化模型时将创建版本。

$post = Post::create(['title' => 'version1', 'content' => 'version1 content']);
$post->update(['title' => 'version2']);

您可以通过在 onNewVersionCreate 上返回 false 来防止创建新的模型版本。要使用此方法,您的模型必须实现与 Versionable 特性相结合的 VersionableInterface

use CapeAndBay\Versionable\Versionable;
use CapeAndBay\Versionable\VersionableInterface;
use Illuminate\Database\Eloquent\Model;

class User extends Model implements VersionableInterface
{
    use Versionable;
    
    public function onNewVersionCreate(Model $model) : bool
    {
        // Create new version if email is not "skip@mail.com"
        return $model->email !== 'skip@mail.com';
    }
}

获取版本

$post->versions; // all versions
$post->latestVersion(); // latest version
$post->versions->first(); // first version