gpt4 book ai didi

Laravel updateOrCreate 函数不更新自定义时间戳

转载 作者:行者123 更新时间:2023-12-02 20:08:22 34 4
gpt4 key购买 nike

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

仅当我使用 updateOrCreate 函数并且仅当唯一要更新的字段是时间戳字段时才会出现此问题。 (在我的例子中,“last_scan”)。例如,当我将“status”更改为 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();
});

最佳答案

TL;DR

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

更深入

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

我再次查看模型,发现 protected $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'];

关于Laravel updateOrCreate 函数不更新自定义时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54157977/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com