laravel - 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();
});
解决方案
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'];
推荐阅读
- python - 如何在 Keras 中使用 float16 微调 resnet50?
- c# - 有什么方法可以反序列化派生类而不在我的模型中创建对 Json.NET 的依赖关系?
- android - 如何根据构建类型和构建风格管理配置
- sockets - ssl握手只能通过客户端证书验证而不是服务器证书验证来建立吗?
- python - 在多个 GPU 上训练单个 pytorch 模型并修复某些层?
- opencv - 当我指定了opencv 4安装的路径后,为什么cmake会在conda环境中链接到opencv?
- visual-studio-code - Visual Studio 代码:如何在当前文件中进行不区分大小写的搜索?
- java - 如何在 Presenters 方法中模拟新创建的对象?
- python - Pandas 数据框在时间范围内过滤行
- sitecore - 删除项目时 Sitecore 重叠错误