gpt4 book ai didi

mysql - Laravel 5 Mysql 重复条目错误

转载 作者:行者123 更新时间:2023-11-29 12:17:19 25 4
gpt4 key购买 nike

我使用 Laravel 5 向数据库中插入一些条目,但出现以下错误:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1' for key 'category_id' (SQL: insert into products (product_name, product_price, category_id) values (asdaszzz, 123, 1))

据我了解,问题是我想在category_id表中添加的值已经存在于其他条目中,但问题是category_id表不是唯一键。下面我发布了迁移:

public function up()
{
Schema::create('products', function($table)
{
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->string('product_name', 255)->unique();
$table->decimal('product_price', 10, 4);
$table->dateTime('updated_at')->default(DB::raw('CURRENT_TIMESTAMP'));
});

Schema::table('products', function($table) {
$table->foreign('category_id')->references('id')->on('categories');
});
}

最佳答案

向category_id添加可为空

$table->integer('category_id')->unsigned()->nullable();

关于mysql - Laravel 5 Mysql 重复条目错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29594966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com