laravel - Eloquent `update()` 方法也更新脏列
问题描述
我注意到当我使用 eloquentupdate()
方法时,它也会更新脏列:
$user = User::find(1);
$user->is_admin = 1;
$user->update(['first_name' => 'Alex']);
//is_admin updated to 1 !
它不应该只更新first_name
列吗?
什么雄辩的方法只更新给定的字段并忽略脏列?
请注意,我知道添加额外查询的方法refresh
和fresh
方法,这不是我寻找的方法。
解决方案
要将模型属性重置为原始属性(从第一个查询或最后一次新鲜/刷新),请使用syncOriginal()
在这种情况下,在更新后使用它将不起作用,因为当您使用模型实例进行更新时,它也会更新脏属性is_admin
(检查您的数据库)。
正如文件定义所示,它仍然->save()
在模型上运行,并将保存更改is_admin
。
/**
* Update the model in the database.
*
* @param array $attributes
* @param array $options
* @return bool
*/
public function update(array $attributes = [], array $options = [])
{
if (! $this->exists) {
return false;
}
return $this->fill($attributes)->save($options);
}
解决方案是忽略该实例并进行新查询
$user = User::find(1);
$user->is_admin = 1;
User::whereKey($user->getKey())->update(['first_name' => 'Alex']);
//you should also set it in the model
$user->first_name = 'Alex';
$user->setOriginalAttribute('first_name', 'Alex');
推荐阅读
- javascript - JavaScript TypeError:合约不是函数
- python - 使用 re.search 在 python 中找不到特定的子字符串
- javascript - 从 React Redux Thunk 返回承诺
- java - [tag][Android/Gradle] 使用 Gradle 任务从 Android 库代码中删除特定风格的库的导入语句
- iphone - Outlook 权限中来自邮箱的共享联系人
- android-studio - 如何在 android studio 上使用草图应用程序源模板?
- android - 在不同的活动中使用相同的 ArrayAdapter?
- r - 包含一个表达式并排除另一个问题的字符串的正则表达式
- xcode - 在我将 Sentry 添加到 react-native 项目后,部署到 iTunes Store 的应用程序崩溃(在 Android 或 ios 模拟器上它工作正常)
- ubuntu - Ubuntu 模拟 URL 以命中虚拟服务器