gpt4 book ai didi

laravel-5 - Eloquent `isDirty()` 和 `getChanges()` 之间的不一致

转载 作者:行者123 更新时间:2023-12-02 19:50:23 27 4
gpt4 key购买 nike

我目前正在处理 Laravel 5.8 项目,在更新模型时注意到,即使模型没有任何更改,我也会将相同的模型保存回数据库中。

为了避免这种情况,我的想法如下:

$model = Model::find($id);
$model->fill([
"name" => $request->name,
...
]);
if($model->isDirty){
$model->save()
}

问题是,即使我没有更改模型中的值,我仍然会进入 if() 条件并保存模型。我尝试使用一个临时变量并调试了 $model->getChanges(),我得到了一个空数组。

这是预期的行为吗?

最佳答案

是有区别的。

相关代码: https://github.com/laravel/framework/blob/6.x/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php#L1060

是脏代码

/**
* Determine if the model or any of the given attribute(s) have been modified.
*
* @param array|string|null $attributes
* @return bool
*/
public function isDirty($attributes = null)
{
return $this->hasChanges(
$this->getDirty(), is_array($attributes) ? $attributes : func_get_args()
);
}

getChanges() 和 getDirty 代码

/**
* Get the attributes that have been changed since last sync.
*
* @return array
*/
public function getDirty()
{
$dirty = [];
foreach ($this->getAttributes() as $key => $value) {
if (! $this->originalIsEquivalent($key, $value)) {
$dirty[$key] = $value;
}
}
return $dirty;
}
/**
* Get the attributes that were changed.
*
* @return array
*/
public function getChanges()
{
return $this->changes;
}

总结一下。

这篇文章中使用的答案:https://laracasts.com/discuss/channels/eloquent/observer-column-update-isdirty-or-waschanged

isDirty (and getDirty) is used BEFORE save, to see what attributes were changed between the time when it was retrieved from the database and the time of the call, while wasChanged (and getChanges) is used AFTER save, to see that attributes were changed/updated in the last save (from code to the database).

进入 isDirty 检查的原因是在检查之前执行 fill()。我认为这将自动填充 updated_at。因此,实际上,在这种情况下,模型已经更改。

关于laravel-5 - Eloquent `isDirty()` 和 `getChanges()` 之间的不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58312036/

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