bytestgear/eloquent-incrementable

此包已被废弃,不再维护。作者建议使用 testmonitor/eloquent-incrementable 包。

在您的 Eloquent 模型中定义一个自定义的自增字段,该字段通过 PHP 而不是数据库引擎来确定。

5.0.0 2023-04-09 15:23 UTC

This package is auto-updated.

Last update: 2024-08-15 09:26:19 UTC


README

Latest Stable Version StyleCI codecov License

在您的 Eloquent 模型中定义一个自定义的自增字段,该字段通过 PHP 而不是数据库引擎来确定。

此外,通过使用自增组,您可以根据其他字段重新开始表中计数。考虑以下示例

想象一个缺陷跟踪应用程序,它将每个缺陷存储在一个单独的表中,但按项目表示。您希望每个项目从新的缺陷计数开始,同时保持唯一的数据库 ID。Incrementable 将使您能够在定义新的 project_id 时自动重置 code 计数器。

目录

安装

此包可以通过 Composer 安装

$ composer require testmonitor/eloquent-incrementable

用法

为了将 Incrementable 添加到您的 Eloquent 模型,您需要

  1. 在您的模型(s)上使用特质 TestMonitor\Incrementable\Traits\Incrementable
  2. 配置自增字段 (注意:确保它是一个整数列)
  3. 可选地,添加一个或多个自增组。

在您想要跟踪的模型上添加 Incrementable 特质

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use TestMonitor\Incrementable\Traits\Incrementable;

class Bug extends Model
{
    use Incrementable, SoftDeletes;

    protected $table = 'bugs';

    protected $incrementable = 'code';

    // This will cause the code to reset once
    // a new project_id is found.
    protected $incrementableGroup = ['project_id'];
}

为了避免冲突,Incrementable 将保留软删除模型的计数。尽管这将在下一个模型之间造成差距,但它将确保在模型恢复时保持唯一性。

示例

在这个例子中,我们设置了以下内容

  • 包含 namecode 字段的表。
  • 一个名为 App\Bug 的 Eloquent 模型,它使用 Incrementable 特质
  • 在 Bug 模型上的一个属性:$incrementable = 'code'

现在我们可以运行这个示例

$bug = new App\Bug(['name' => 'It doesn\'t work.']);
$bug->save();

// Will show '1'
echo $bug->code;

$bug = new App\Bug(['name' => 'It really doesn\'t work.']);
$bug->save();

// Will show '2'
echo $bug->code;

测试

此包包含集成测试。您可以使用 PHPUnit 运行它们。

$ vendor/bin/phpunit

变更日志

有关更多信息,请参阅 CHANGELOG

贡献

有关贡献详细信息,请参阅 CONTRIBUTING

鸣谢

许可证

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