【发布时间】:2017-10-01 17:20:28
【问题描述】:
尝试在模型 (ProductItem) 上调用 firstOrCreate() 两次后出现以下错误,表示具有主键和唯一键的架构:
Illuminate\Database\QueryException 带有消息“SQLSTATE[23000]: 完整性约束违规:1062 键的重复条目“1000” 'product_items_item_ref_id_unique'(SQL:插入
product_items(item_ref_id,name,updated_at,created_at) 值 (1000, '项目 1', 2017-05-03 19:20:26, 2017-05-03 19:20:26))'
- 首次运行时,我预计 firstOrCreate() 会尝试 获取一个项目,否则如果它不存在,它创建 (插入)并返回一个新的。
- 如果我第二次运行,我认为它应该返回现有的。
迁移如下:
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');
}
}
用于创建项目的代码:
$product_item = App\ProductItem::firstOrCreate(['item_ref_id'=>1000,'name'=>'Item 1')] );
我浏览了以下帖子,但都没有帮助
【问题讨论】:
-
如果您从 'item_ref_id' 中删除唯一约束会发生什么?
-
firstOrCreate离开id字段。如果您希望item_ref_id成为您的主键,请将其定义为具有指定值的主键并删除增量列。如果您希望item_ref_id成为自动增量列,请更改增量 id,并确保在模型中设置 primaryKey。 -
@aynber 我希望
item_ref_id是唯一键,而不是主键,id是主键。 -
出于好奇,如果您删除
'name' => 'Item1'并仅保留 ref id 作为搜索参数会怎样?
标签: php mysql laravel eloquent laravel-migrations