php - Eloquent updateOrCreate 总是创建

标签 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');
        });

我的 $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());

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

最佳答案

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

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

所以我猜Jesus answer可能适合您。

关于php - Eloquent updateOrCreate 总是创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55839663/

相关文章:

mysql - 如果存在则更新 MySQL

c# - 使用 MySQL 的 EF5 Code First GUID

javascript - 从nodejs上传本地文件到Laravel服务器时获取null

php - Laravel 独白。记录 INFO 级别到单独的文件

php - 如何使用 linkedin v2 api 获取电子邮件地址?

php - 输入键以保存文本区域值

javascript - 在 Angular JS 中同时发送表单数据和上传文件

mysql - 从数据库计算唯一用户

php - 按 2 列的平均值过滤的 Eloquent 方式

php - PHP 中的退出状态仅在从命令行运行时有用吗?