首页 > 解决方案 > Eloquent `update()` 方法也更新脏列

问题描述

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

$user = User::find(1);

$user->is_admin = 1;

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

//is_admin updated to 1   !

它不应该只更新first_name列吗?

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

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

标签: laravel

解决方案


要将模型属性重置为原始属性(从第一个查询或最后一次新鲜/刷新),请使用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');

推荐阅读