2015-04-12 72 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'); 
    }); 
}