我在我的應用程式中使用 UUID,並且我已經實現了該特徵,如在線所示,如下所示:
trait Uuid
{
protected static function boot(): void
{
parent::boot();
static::creating(function (Model $model) {
if (!$model->getKey()) {
$model->{$model->getKeyName()} = (string) Str::uuid();
}
});
}
public function getIncrementing(): bool
{
return false;
}
public function getKeyType(): string
{
return 'string';
}
}
回想起來,這幾乎適用於任何地方:我正在嘗試在我的產品上建立資料透視表,如下所示:
public function categories(): BelongsToMany
{
return $this->belongsToMany(
Category::class,
ProductCategory::class,
'product_id',
'category_id'
);
}
遷移如下圖所示:
public function up(): void
{
Schema::create('product_categories', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignUuid('product_id')->index();
$table->foreignUuid('category_id')->index();
$table->timestamps();
});
}
但是,每當我在播種時執行以下操作:
Product::first()->categories()->sync(Categories::all()->pluck('id'));
我看到這個錯誤:
PDOException::(“SQLSTATE[HY000]:一般錯誤:1364 欄位「id」沒有預設值」)
Category 和 ProductCategory 都使用 Uuidd 特徵,我不知道如何使其工作。
感謝任何幫助。
作為可能的解決方案之一,您可以使用自己的模型和資料透視表的特徵。
更多: https://laravel.com/docs/ 9.x/eloquent-relationships#defining-custom-intermediate-table-models。