audunru/model-history

记录Laravel模型的变更

v2.1.0 2024-07-16 18:39 UTC

README

Build Status Coverage Status StyleCI

记录应用中模型的变化。如果用户将产品的名称从A更改为B,这个变化将被存储在一个名为Change的模型中,并存储在您的数据库中。只有更改的属性会被存储。然后您可以使用它来检索模型的历史记录,包括哪个用户进行了更改。

安装

步骤 1:使用Composer安装

composer require audunru/model-history

步骤 2:发布并运行迁移

注意:更改被存储在名为history的表中。您可以在配置中更改此设置,但在发布和运行迁移之前,您必须先发布配置。

php artisan vendor:publish --tag=model-history-migrations
php artisan migrate

步骤 3:为您的模型添加特质

MakesChanges特质添加到您的User模型中

namespace App\Models;

use audunru\ModelHistory\Traits\MakesChanges;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use MakesChanges;

HasHistory特质添加到您希望跟踪变化的任何模型中

namespace App\Models;

use audunru\ModelHistory\Traits\HasHistory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasHistory;

步骤 4:检索模型变更

假设您已将HasHistory特质添加到名为Product的模型中,您可以这样检索变更

$product = Product::create([
    'description' => 'Old description',
]);

$product->update([
    'description' => 'New description',
]);

dump($product->changes);

配置

通过运行以下命令发布配置文件

php artisan vendor:publish --tag=model-history-config

可用选项

    /*
     * Table where the "Change" model will be stored
     */
    'history_table_name' => 'history',
    /*
     * Eager load the change model's owner
     */
    'eager_load_owner' => true,
    /*
     * Eager load the change model's model
     */
    'eager_load_model' => false,
    /*
     * Date format used when returning the Change model as JSON
     */
    'date_format' => 'Y-m-d H:i:s',

开发

测试

运行测试

composer test