Laravel Eloquent update just if changes have been made

前端 未结 3 716
时光说笑
时光说笑 2020-12-02 10:21

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 goo

3条回答
  •  我在风中等你
    2020-12-02 10:48

    You're already doing it!

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

    Here's the relevant part of code in Illuminate\Database\Eloquent\Model@performUpdate:

    protected function performUpdate(Builder $query, array $options = [])
    {
        $dirty = $this->getDirty();
    
        if (count($dirty) > 0)
        {
            // runs update query
        }
    
        return true;
    }
    

    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;
    }
    

    If you want to check if the model is dirty just call isDirty():

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

    Or if you want to check a certain attribute:

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

提交回复
热议问题