Dirty()在Laravel中是什么意思


What does isDirty() mean in Laravel?

首先,我对Laravel不太熟悉(或者对"脏"这个词不太熟悉)
我偶然发现了这行代码——

if ($this->isDirty('status')) {
    if (Notification::has('website-status-' . strtolower($this->status))) {
        Notification::set($this->account, 'website-status-' . strtolower($this->status), $this->emailAttributes())
            ->email();
    }
}

我不明白这到底意味着什么。我试着在互联网上找到,但Laravel网站只说这个

"确定给定属性是否脏"

这并没有真正的帮助。。。

当您想知道模型从数据库中查询后是否已编辑,或者根本没有保存时,可以使用->isDirty()函数。

isDirty方法确定自加载模型以来是否更改了任何属性。您可以传递一个特定的属性名称,以确定特定的属性是否脏。

    $user = User::create([
        'first_name' => 'Amir',
        'last_name' => 'Kaftari',
        'title' => 'Developer',
    ]);
    $user->title = 'Jafar';
    $user->isDirty(); // true
    $user->isDirty('title'); // true
    $user->isDirty('first_name'); // false

Eloquent提供了isDirtyisCleanwasChanged方法来检查模型的内部状态,并确定其属性与最初加载时相比发生了怎样的变化。

您可以在官方文件中找到这三种方法的完整描述和示例:https://laravel.com/docs/9.x/eloquent#examining-属性更改

作为对已接受答案的支持:

$model = Model::find(1);
$model->first_column = $request->first_value;
$model->second_column = $request->second_value;
$model->third_column = $request->third_value;
if($model->isDirty()){
// the model has been edited, else codes here will not be executed
}
$model->save();