I am getting the following error after trying to call firstOrCreate() twice on a Model (ProductItem), representing a Schema with a primary key AND a unique key:
Illuminate\Database\QueryException with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1000' for key 'product_items_item_ref_id_unique' (SQL: insert into
product_items
(item_ref_id
,name
,updated_at
,created_at
) values (1000, 'Item 1', 2017-05-03 19:20:26, 2017-05-03 19:20:26))'
- On first run, I would expect that firstOrCreate() would attempt to fetch for an item, otherwise if it does not exist, it creates (inserts) and returns a new one. <- it inserts successfully
- If I run it a second time, I assume it should return the existing one. <- this is where the error occurs
The migration is as follows:
class CreateProductItemTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('product_items', function (Blueprint $table) {
$table->increments('id');
$table->integer('item_ref_id')->unique();
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('product_items');
}
}
The code used to create the item:
$product_item = App\ProductItem::firstOrCreate(['item_ref_id'=>1000,'name'=>'Item 1')] );
I have gone through the following posts, none of which have helped