xt/laravel-external-id

保存 Eloquent 模型时生成外部 ID

v1.0.1 2022-06-29 07:55 UTC

This package is auto-updated.

Last update: 2024-09-29 05:22:32 UTC


README

本包提供了一个特质,用于在保存任何 Eloquent 模型时生成一个公共使用 ID。

$model = new EloquentModel();
$model->save();

echo $model->external_id; // ouputs "activerecord-is-awesome"

安装

您可以通过 composer 安装此包

composer require xt/laravel-external-id

用法

您的 Eloquent 模型应使用 XT\ExternalId\HasExternalId 特质和 XT\ExternalId\ExternalIdOptions 类。

特质包含一个抽象方法 getExternalIdOptions(),您必须自行实现。

您的模型迁移应包含一个字段来保存生成的外部 ID。

以下是如何实现该特质的示例

namespace App;

use XT\ExternalId\HasExternalId;
use XT\ExternalId\ExternalIdOptions;
use Illuminate\Database\Eloquent\Model;

class YourEloquentModel extends Model
{
    use HasExternalId;

    /**
     * Get the options for generating the slug.
     */
    public function getExternalIdOptions() : ExternalIdOptions
    {
        return ExternalIdOptions::create()
            ->saveExternalIdTo('external_id');
    }
}

及其迁移

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateYourEloquentModelTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('your_eloquent_models', function (Blueprint $table) {
            $table->increments('id');
            $table->string('external_id'); // Field name same as your `saveExternalIdTo`
            $table->string('name');
            $table->timestamps();
        });
    }
}

要使用外部 ID 获取记录,可以使用 findByExternalId 方法

YourEloquentModel::findByExternalId('<Your-ID>');

许可协议

MIT 许可协议 (MIT)。请参阅 许可文件 了解更多信息。