【问题标题】:Eloquent updateOrCreate always create雄辩的 updateOrCreate 总是创建
【发布时间】:2019-04-24 22:59:33
【问题描述】:

我正在尝试使用 updateOrCreate 来简化我的代码,但函数总是创建一个新行,从不更新。

我的迁移:

        Schema::create('logs', function (Blueprint $table) {
         $table->bigIncrements('id');
         $table->integer('project_id')->unsigned();
         $table->datetime('is_fixed')->nullable();
         $table->datetime('snooze_until')->nullable();
         $table->integer('snooze_while')->nullable();
         $table->string('title', 100);
         $table->string('level', 100);
         $table->string('description');
         $table->string('stage',100);
         $table->json('details')->nullable();
         $table->timestamps();

         $table->foreign('project_id')->references('id')->on('projects');
        });

我的 $fillables

protected $fillable = [
    'project_id', 
    'is_fixed', 
    'snooze_until', 
    'snooze_while', 
    'title', 
    'level', 
    'description', 
    'stage',
    'details'
];

我的测试

    $log = new Log();

    $log->fill([
        'title' => 'Vicente\\Sally\\Schiller',
        'level' => 'ERROR',
        'description' => 'Laboriosam et architecto voluptatem.',
        'stage' => 'production@wender-fedora',
        'details' => '{"app":"MyApp"}',
        'project_id' => 5
    ]);

    Log::updateOrCreate($log->toArray());

我有一些可以为空的字段,但我认为这不是问题。

【问题讨论】:

    标签: php mysql laravel eloquent


    【解决方案1】:

    updateOrCreate 方法接受两个数组参数:

    • 第一个是字段数组 =>将用作检查行是否存在的条件。
    • 第二个是字段数组 => 要更新的值(如果记录与第一个参数中的条件匹配)或要添加(在未找到匹配的情况下与第一个参数合并) .

    所以我猜Jesus answer 可能是适合你的。

    【讨论】:

      【解决方案2】:

      你想试试这个:

          Log::updateOrCreate(
              [
                  'title' => 'Vicente\\Sally\\Schiller',
                  'project_id' => 5
              ], 
              [
                  'title' => 'Vicente\\Sally\\Schiller',
                  'level' => 'ERROR',
                  'description' => 'Laboriosam et architecto voluptatem.',
                  'stage' => 'production@wender-fedora',
                  'details' => '{"app":"MyApp"}',
                  'project_id' => 5
              ]
          );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-08-14
        • 1970-01-01
        • 2023-02-04
        • 1970-01-01
        • 2019-07-17
        • 1970-01-01
        • 2018-05-19
        相关资源
        最近更新 更多