gpt4 book ai didi

laravel - Eloquent `update()` 方法也更新脏列

转载 作者:行者123 更新时间:2023-12-03 08:14:59 25 4
gpt4 key购买 nike

我注意到当我使用 Eloquent update() 方法时,它也会更新脏列:

$user = User::find(1);

$user->is_admin = 1;

$user->update(['first_name' => 'Alex']);

//is_admin updated to 1 !

它不应该只更新 first_name 列吗?

什么 Eloquent 方法只更新给定的字段并忽略脏列?

请注意,我知道 refreshfresh 方法,它们添加了额外的查询,这不是我寻找的方法。

最佳答案

要将模型属性重置为原始属性(从第一个查询或最后一次刷新/刷新),请使用 syncOriginal()

在这种情况下更新后使用时它将不起作用,因为当您使用模型实例进行更新时,它还会更新脏属性is_admin(检查您的数据库) )。

作为file definition显示,它仍然在模型上运行 ->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');

关于laravel - Eloquent `update()` 方法也更新脏列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69687819/

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