Laravel 5 Mysql重复输入错误

时间:2015-04-12 21:41:00

标签: mysql laravel-5

我使用Laravel 5将一些条目插入数据库但是我收到以下错误:

  

SQLSTATE [23000]:完整性约束违规:1062重复条目' 1'对于key' category_id' (SQL:插入productsproduct_nameproduct_pricecategory_id)值(asdaszzz,123,1))

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

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');
    });
}

2 个答案:

答案 0 :(得分:2)

将nullable添加到category_id

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

答案 1 :(得分:-1)

尝试添加表格密钥...

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'));

        $table->index('category_id');

        $table->foreign('category_id')->references('id')->on('categories');
    });
}