2015-04-12 73 views
0

我使用Laravel 5到数据库中插入一些条目,但我得到以下错误:Laravel 5个MySQL重复录入错误

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表中添加allready已存在于其他条目中,但事实是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'); 
    }); 
} 

回答

1

添加可空至CATEGORY_ID

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

谢谢,似乎是工作。为什么可以为空来解决问题? – Netra

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