Laravel雄辩更新只要改变了 [英] Laravel Eloquent update just if changes have been made

查看:82
本文介绍了Laravel雄辩更新只要改变了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用雄辩的模型来更新Laravel的记录,只要这个记录发生了变化?我不希望任何用户一遍又一遍地要求数据库没有好的理由,只需点击按钮来保存更改。我有一个 javascript 功能,根据页面中是否有更改启用和禁用保存按钮,但我想知道是否可以确保执行此操作服务器端的一些功能也是。我知道我可以通过自己完成它(意思是:没有呼吁框架的内部功能),只要检查记录是否有变化,但在这样做之前,我想知道Laravel雄辩模型是否已经处理所以我不需要重新发明轮。

Is there any way to update a record in Laravel using eloquent models just if a change has been made to that record? I don't want any user requesting the database for no good reason over and over, just hitting the button to save changes. I have a javascript function that enables and disables the save button according with whether something has changed in the page, but I would like to know if it's possible to make sure to do this kind of feature on the server side too. I know I can accomplish it by myself (meaning: without appealing to an internal functionality of the framework) just by checking if the record has change, but before doing it that way, I would like to know if Laravel eloquent model already takes care of that, so I don't need to re-invent the wheel.

这是我用来更新记录的方式:

This is the way I use to update a record:

$product = Product::find($data["id"]);
$product->title = $data["title"];
$product->description = $data["description"];
$product->price = $data["price"];
//etc (string values were previously sanitized for xss attacks)
$product->save();


推荐答案

你已经在做了!

save()将检查模型中是否有更改。如果没有,它将不会运行数据库查询。

save() will check if something in the model has changed. If it hasn't it won't run a db query.

以下是 Illuminate\Database\Eloquent\\中的代码的相关部分\\Model @ performUpdate

protected function performUpdate(Builder $query, array $options = [])
{
    $dirty = $this->getDirty();

    if (count($dirty) > 0)
    {
        // runs update query
    }

    return true;
}






getDirty()方法在创建模型时,将当前属性与保存在原始中的副本进行比较。这是在 syncOriginal()方法中完成的:


The getDirty() method simply compares the current attributes with a copy saved in original when the model is created. This is done in the syncOriginal() method:

public function __construct(array $attributes = array())
{
    $this->bootIfNotBooted();

    $this->syncOriginal();

    $this->fill($attributes);
}

public function syncOriginal()
{
    $this->original = $this->attributes;

    return $this;
}






如果要检查如果模型是脏的,只需调用 isDirty()

if($product->isDirty()){
    // changes have been made
}

或者如果你想检查某个属性:

Or if you want to check a certain attribute:

if($product->isDirty('price')){
    // price has changed
}

这篇关于Laravel雄辩更新只要改变了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆