播种时完整性约束违规

时间:2018-01-05 10:19:13

标签: php laravel-5.4

我正在使用laravel 5.4。一个产品属于一个类别,一个类别可以有一个产品。每个表都有一个uuid作为主键。 播种时我收到此错误:

Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`awesome`.`product`, CONSTRAINT `product_category_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`))

error message

我不知道自己做错了什么。提前谢谢。

这是类别模型

class Category extends Base {
    protected $table = 'category';

    protected $primaryKey = 'id';

    protected $fillable = ['id', 'name'];

    public function products(){
        return $this->hasMany('App\Model\Product');
    }
}

这是产品型号

class Product extends Base {
    protected $table = 'product';

    protected $primaryKey = 'id';

    protected $fillable = [
        'id',
         ...,
        'category_id'
    ];

    public function category()
    {
        return $this->belongsTo('App\Model\Category');
    }
}

产品迁移

 public function up()
{
    Schema::create('product', function (Blueprint $table) {
        $table->uuid('id');
        $table->primary('id');
        $table->uuid('category_id');
        $table->foreign('category_id')->references('id')->on('category');
        $table->timestamps();
    });
}

类别迁移

public function up()
{
    Schema::create('category', function (Blueprint $table) {
        $table->uuid('id');
        $table->primary('id');
        $table->string('name');
        $table->timestamps();
    });
}

产品工厂

$factory->define(App\Model\Product::class, function (Faker\Generator $faker) {
    return [
        'id' => \Faker\Provider\Uuid::uuid(),
        'category_id' => function() {
            return factory(App\Model\Category::class)->create()->id;
        },
    ];
});

类别工厂

$factory->define(App\Model\Category::class, function (Faker\Generator $faker) {
    return [
        'id' => \Faker\Provider\Uuid::uuid(),
        'name' => $faker->word,
    ];
});

数据库播种机

public function run()
{
    factory(\App\Model\Category::class, 5)->create()->each (function ($category) {
       factory(\App\Model\Product::class, 5)->create(['category_id' => $category->id]);
    });

}

1 个答案:

答案 0 :(得分:0)

我想我已经明白了发生了什么。因为主键的名称是' id'它被认为是一个整数,并在我写$ category-> id时转换为整数,它给出了0。所以在Category表中没有行,0为id。只需要更改主键的名称。