我在我的应用程序中使用 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 特征,我不知道如何使其工作。
感谢任何帮助。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
作为可能的解决方案之一,您可以使用自己的模型和数据透视表的特征。
更多: https://laravel.com/docs/ 9.x/eloquent-relationships#defining-custom-intermediate-table-models。