【问题标题】:Integrity constraint violation firstOrCreate()违反完整性约束 firstOrCreate()
【发布时间】: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))'

  1. 首次运行时,我预计 firstOrCreate() 会尝试 获取一个项目,否则如果它不存在,它创建 (插入)并返回一个新的。
  2. 如果我第二次运行,我认为它应该返回现有的。

迁移如下:

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

我浏览了以下帖子,但都没有帮助

  1. laravel first0rNew Integrity Constraint Violation
  2. Laravel 5 Integrity constraint violation
  3. Laravel - Integrity constraint violation: 1062 Duplicate entry

【问题讨论】:

  • 如果您从 '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


【解决方案1】:

我相信你有语法问题。 documentation 描述语法如下:

$flight = App\Flight::firstOrCreate(
    ['name' => 'Flight 10'], ['delayed' => 1]
);

请注意,这些字段位于不同的数组中,而不是同一数组中的两个元素。试一试。所以对你来说是:

$product_item = App\ProductItem::firstOrCreate(['item_ref_id'=>1000], ['name'=>'Item 1')] );

【讨论】:

  • 您的语法可能也应该起作用,因为我注意到文档在 updateOrCreate() 示例中使用了它。在这种情况下,就会出现不同的问题。
猜你喜欢
  • 2020-01-14
  • 2021-12-13
  • 2019-04-12
  • 1970-01-01
  • 2020-04-08
  • 2016-04-13
  • 2019-10-20
相关资源
最近更新 更多