Laravel Eloquent只有在做出更改后才会更新

use*_*140 69 php laravel eloquent

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

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

$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();
Run Code Online (Sandbox Code Playgroud)

luk*_*ter 142

你已经在做了!

save()将检查模型中的某些内容是否已更改.如果没有它将不会运行数据库查询.

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

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

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

    return true;
}
Run Code Online (Sandbox Code Playgroud)

getDirty()方法只是将当前属性与original创建模型时保存的副本进行比较.这是通过以下syncOriginal()方法完成的:

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

    $this->syncOriginal();

    $this->fill($attributes);
}

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

    return $this;
}
Run Code Online (Sandbox Code Playgroud)

如果要检查模型是否脏,请调用isDirty():

if($product->isDirty()){
    // changes have been made
}
Run Code Online (Sandbox Code Playgroud)

或者,如果要检查某个属性:

if($product->isDirty('price')){
    // price has changed
}
Run Code Online (Sandbox Code Playgroud)

  • 对于阅读此书的人,请务必在使用“ isDirty()”之前签出[this answer](http://stackoverflow.com/questions/36329850/laravel-5-isdirty-always-returns-false#answer-36330079)。 。 (2认同)
  • 有“getChanges()”方法。检查我的答案/sf/answers/3789251441/ (2认同)

Ahm*_*sef 10

我想添加此方法,如果您使用的是编辑表单,则可以使用此代码保存update(Request $request, $id)函数中的更改:

$post = Post::find($id);    
$post->fill($request->input())->save();
Run Code Online (Sandbox Code Playgroud)

请记住,您必须使用相同的列名称命名输入.该fill()功能将为您完成所有工作:)

  • 这实际上是我正在寻找的答案,我忘记了名称`fill`,以及如何批量传递请求.谢谢!我不需要传递ID,因为即时更新,所以它已经有`$ request-> id`. (2认同)

Mla*_*vic 7

getChanges()即使持久化后,也可以在Eloquent模型上使用。