eloquent - 不触及某些字段的时间戳
问题描述
我有几个带有时间戳和active
字段的模型,以及我更新它们的代码中的几个部分。我希望能够更新模型,并且仅在更新的模型更改大于活动字段时才触摸时间戳。所以我的代码是
const leaveUntouched=["active"=>true]
...
$instance = $model::find($data["id"]);
$changed = array_diff_assoc($data,$instance->toArray());
$needTimestampTouch = array_diff_key($changed,self::leaveUntouched);
if (empty($needTimestampTouch))
$instance->timestamps = false;
$instance->fill($data);
$instance->save();
如果我可以在 BaseModel 本身中定义它,它会更干净。我应该在我的基类中扩展 Eloquent/Model 的填充方法吗?我该怎么做?
解决方案
For reference:
I put this in my Baseclass and it works:
protected $preventTouch=['active'];
public function save(array $options = [])
{
$needsUpdate=array_diff(
array_keys($this->getDirty()),
$this->preventTouch
);
$this->timestamps = count($needsUpdate) > 0;
parent::save($options);
}
推荐阅读
- sql - 如何按另一个表中的外键值的数量对一个表进行排序?
- excel - 如何对范围内同一行的单元格应用 COUNTIFS 公式
- javascript - 仅在播放器暂停时显示元素
- c++ - 如何将我的 UWP 页面设置为在启动时具有恒定的宽度和高度?
- tor - 是否可以将 Mattermost 实例作为洋葱服务运行?
- c - 递归:如何保持 for 循环中不断变化的变量在递归期间不发生变化?
- vue.js - 尝试从 vuejs 组件调度动作时,vuex 未知动作类型
- html - 如何使用 css 为 html 字符添加边框颜色?
- sql-server - 用户会话卡在killed\rollback 状态
- unity3d - Unity:索引问题超出了数组的范围