Laravel 拉维种子';带uuid的s
我的种子有问题。以下是我的表格结构:Laravel 拉维种子';带uuid的s,laravel,migration,primary-key,uuid,seed,Laravel,Migration,Primary Key,Uuid,Seed,我的种子有问题。以下是我的表格结构: 1.Complaints: Schema::create('complaints', function (Blueprint $table) { $table->uuid('id'); $table->unsignedInteger('origin_id'); $table->timestamps(); $table->primary('id');
1.Complaints:
Schema::create('complaints', function (Blueprint $table) {
$table->uuid('id');
$table->unsignedInteger('origin_id');
$table->timestamps();
$table->primary('id');
});
2.Complaint_bill
Schema::create('complaint_bills', function (Blueprint $table) {
$table->uuid('complaint_id');
$table->string('symbol')->nullable();
$table->string('item_name');
$table->timestamps();
$table->primary('complaint_id');
$table->foreign('complaint_id')->references('id')-
>on('complaints');
现在我有了种子:
factory(Complaint::class, 10)->create()->each(function ($c) {
$product = Product::inRandomOrder()->first();
factory(ComplaintBill::class, 10)->create([
'complaint_id' => $c->id,
'item_id' => $product->id,
'item_name' => $product->name,
'item_numeric_index' => $product->numeric_index,
'item_gross_price' => $product->sell_price_gross,
]);
})'
我有这样的问题/错误:
SQLSTATE[23505]: Unique violation: 7 ERROR: duplicate key value
violates u
nique constraint "complaint_bills_pkey"
DETAIL: Key (complaint_id)=(ea302ab8-67dc-3bed-afc8-4215a99f1f68)
already exists.
当我在投诉单(列-投诉id)中评论primary时,一切都正常。看起来问题是我在投诉单上有uuid的主键,这是投诉单上的foregin->id。为什么会这样?当我与两个主键相关时,我不能在foregin上使用primary?您看到这个问题的原因是UUID不是一个自动递增的值,传统意义上,定义主键时是一个整数自动递增。使用factory方法插入一组数据时,值不会在每次插入时自动“增加一” 您需要初始化使用引导函数生成的每个模型,以便在存储之前为自己生成UUID。从以下文章:
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->{$model->getKeyName()} = Uuid::generate()->string;
});
}
下面的文章将对此进行更详细的解释
是否为
投诉
与投诉账单的关系
是否为一家公司
关系?如果是,您不应在投诉单
表中将投诉id
设置为主键
。将字段设置为主键
意味着不存在任何重复项。您是对的-存在关系ONETONE,这就是问题所在。Thks for Advice这是一个很好的解决方案,但与文章建议的依赖第三方库不同,您可以use illumb\Support\Str
和Str::uuid()
生成uuid。嗯。