我的种子有问题。这是我的表结构:

 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(列 - 投诉 ID)中评论主要时,一切正常。看起来问题是我在 Complaint_bill 上的 uuid 上有主键,它是在 Complaint->id 上的。为什么会这样?当我与两个小学有关系时,我不能在 foregin 上有小学吗?

最佳答案

您看到此问题的原因是 UUID 不是定义主键时 INTEGER AUTO_INCREMENT 传统意义上的自动递增值。当使用工厂方法插入一组数据时,值不会在每次插入时自动“增加一个”。

您需要初始化使用引导函数生成的每个模型,以便在存储之前为自己生成 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

关于带有 uuid 的 Laravel 种子,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48456603/

10-16 16:23