Laravel使用UUID填充种子数据

4
我有关于我的种子的问题。这是我的表结构:
```html

...

```
请注意,保留了HTML标签。
 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. 

当我在Complaint_bill(列 - complaint_id)中评论主键时,一切正常。看起来问题在于我在Complaint_bill上有一个uuid的主键,而这个uuid是Complaint->id的外键。为什么会这样做呢?当我有两个主键关系时,我不能在外键上设置主键吗?


1
关系“complaint”和“complaint_bills”是“OneToMany”关系吗?如果是,您不应该在“complaint_bills”表上将“complaint_id”设置为“primary key”。将字段设置为“primary key”意味着没有任何重复。 - Dharma Saputra
你是对的 - 存在一对一的关系,这就是问题所在。感谢建议。 - wenus
2个回答

3
您看到这个问题的原因是UUID不像INTEGER AUTO_INCREMENT定义主键时那样自动增加。当使用工厂方法插入一组数据时,该值不会在每次插入时自动“加1”。
您需要使用引导函数初始化每个生成的模型以为自己生成UUID,并在存储之前进行初始化。参考下面的文章:
protected static function boot()
{
    parent::boot();

    static::creating(function ($model) {
        $model->{$model->getKeyName()} = Uuid::generate()->string;
    });
}

以下文章会更详细地解释这个问题。 https://medium.com/@steveazz/setting-up-uuids-in-laravel-5-552412db2088

2
这是一个不错的解决方案,但与文章建议依赖第三方库不同,您可以使用Illuminate\Support\Str;Str::uuid()来生成UUID。希望对您有所帮助。 - Ted Stresen-Reuter

1
尝试一下:\Ramsey\Uuid\Uuid::uuid4()->toString()
`DB::table('customers')->insert([    

    ['id' => \Ramsey\Uuid\Uuid::uuid4()->toString(), 'name' => 'Test', 'color' => '#aaa', 'created_at' => $now],  
]);`  

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接