Laravel Eloquent update just if changes have been made

前端 未结 3 713
时光说笑
时光说笑 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:45

    You can use getChanges() on Eloquent model even after persisting.

    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 2020-12-02 11:00

    I like to add this method, if you are using an edit form, you can use this code to save the changes in your update(Request $request, $id) function:

    $post = Post::find($id);    
    $post->fill($request->input())->save();
    

    keep in mind that you have to name your inputs with the same column name. The fill() function will do all the work for you :)

    0 讨论(0)
提交回复
热议问题