首页 > 解决方案 > Laravel updateOrCreate 函数不更新自定义时间戳

问题描述

我正在使用 updateOrCreate 函数来创建新行或根据给定值更新存在。但是,当我尝试更新定义为时间戳的值(不是默认的“created_at”或“updated_at”)时,它不会更新该值。

仅当我使用 updateOrCreate 函数并且仅当要更新的唯一字段是时间戳字段时,才会出现此问题。(在我的情况下,'last_scan')。例如,当我将“状态”更改为 0 时,数据库中更新的所有值都包含“last_scan”字段。

我想验证每次运行此函数时,无论是否有数据要更新,last_scan 都会更新到函数运行的时间。

$categoryEntity = CategoryEntity::updateOrCreate(
    [
        'store_id'  => $this->store_id,
        'remote_id' => $collection->id
    ],
    [
        'remote_parent_id'  => 0,
        'name'              => $collection->title,
        'status'            => 1,
        'last_scan'         => Carbon::now()
    ]
);

我尝试使用以下常规更新方法替换更新并创建,并且效果很好:

$categoryEntity->last_scan = Carbon::now();
$categoryEntity->save();

我的迁移文件如下:

Schema::create('categories_entities', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('store_id');
            $table->integer('remote_id');
            $table->integer('remote_parent_id');
            $table->string('name');
            $table->integer('status');
            $table->timestamp('last_scan');
            $table->timestamps();
});

标签: laravellaravel-5eloquent

解决方案


TL;博士

模型中的“受保护的 $fillable”属性不包含“last_scan”字段。

更多深入

经过一番搜索,我注意到 createOrUpdate 方法使用了批量更新功能。$fillable 属性必须包含我们希望提供一个选项来批量更改它们的所有字段。

我再次查看模型并注意到受保护的 $fillable 属性包含除“last_scan”之外的所有字段。

曾是:

protected $fillable = ['store_id', 'remote_id', 'remote_parent_id', 'name', 'status'];

现在:

protected $fillable = ['store_id', 'remote_id', 'remote_parent_id', 'name', 'status', 'last_scan'];


推荐阅读