phpcollective/tracker

跟踪您的Eloquent模型

v1.0.3 2024-05-03 10:54 UTC

This package is auto-updated.

Last update: 2024-10-03 12:08:46 UTC


README

Latest Version on Packagist Software License Total Downloads

默认情况下,Eloquent会自动管理表中的created_atupdated_at列。除此之外,如果模型使用“软删除”,它还会管理一个deleted_at属性。但是,管理谁创建/更新模型以及删除(如果软删除)是非常繁琐的工作。这也表明了代码重复。

如果您希望由Eloquent自动管理这些,使用Tracker是一个方便的方法。

安装

您可以使用Composer将此包安装到Laravel项目中

composer require phpcollective/tracker
Laravel 5.5+

如果您不使用自动发现,请将ServiceProvider添加到config/app.php中的providers数组中

PhpCollective\Tracker\TrackingServiceProvider::class,

数据库:迁移

要跟踪表中您想要跟踪的created_byupdated_by列,只需在表迁移文件中使用$table->track()方法。如果需要删除列,请使用$table->dropTrack()

Schema::create('table', function (Blueprint $table) {
    ...
    $table->track();
});

// To drop columns
Schema::table('table', function (Blueprint $table) {
    $table->dropTrack();
});

如果您的表中包含软删除列,只需在方法中传递布尔值true。它将在数据库中添加一个deleted_by列。

Schema::create('table', function (Blueprint $table) {
    ...
    $table->softDeletes();
    $table->track(true);
});

// To drop columns with soft delete
Schema::table('table', function (Blueprint $table) {
    $table->dropTrack(true);
});

模型

在您想要跟踪的模型中添加Trackable特质。现在它将处理所有由认证用户触发的CRUD事件。

<?php

namespace App;

use PhpCollective\Tracker\Trackable;
use Illuminate\Database\Eloquent\Model;

class Foo extends Model
{
    use Trackable;
    
    ...
}

用法

Trackable特质提供了与认证用户的三种belongsTo关系。creator()editor()destroyer()

$foo = App\Foo::first();
$foo->creator;
$foo->editor;
// If your model use soft delete
$foo->destroyer;

感谢

许可

Laravel Model Tracker是开源软件,受MIT许可许可。