雄辩的updateOrCreate总是创建

Wen*_*ick 0 php mysql laravel eloquent

我试图使用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');
        });
Run Code Online (Sandbox Code Playgroud)

我的$ fillables

protected $fillable = [
    'project_id', 
    'is_fixed', 
    'snooze_until', 
    'snooze_while', 
    'title', 
    'level', 
    'description', 
    'stage',
    'details'
];
Run Code Online (Sandbox Code Playgroud)

我的测试

    $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());
Run Code Online (Sandbox Code Playgroud)

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

小智 6

updateOrCreate方法采用两个数组参数:

  • 第一个是字段=> values的数组,将用作检查该行是否存在的条件。
  • 第二个是字段数组=>要更新的值(如果记录与第一个参数的条件匹配)或要添加的值(如果找不到匹配项,则与第一个参数合并)。

因此,我想耶稣的答案可能是您的正确答案