在laravel中保存vs更新

Par*_*nia 25 laravel-5

是什么区别保存()更新()在Laravel方法.

我在更新查询的情况下使用了save()方法,但在少数情况下它充当更新,在少数情况下它充当插入查询功能.请让我知道它们之间究竟有什么区别.

Gin*_*ane 40

这些方法都允许您将数据保存到数据库中.

当您创建当前未在数据库表中显示的新模型时,该save()方法会形成perfroms INSERT:

 $flight = new Flight;

 $flight->name = $request->name;

 $flight->save(); // it will INSERT a new record
Run Code Online (Sandbox Code Playgroud)

UPDATE当您的模型已存在于数据库中时,它也可以表现得像.所以你可以获得模型,修改一些属性,然后save()实际执行db UDPATE:

$flight = App\Flight::find(1);

$flight->name = 'New Flight Name';

$flight->save(); //this will UPDATE the record with id=1
Run Code Online (Sandbox Code Playgroud)

一种update()方法允许您以更方便的方式更新模型:

App\Flight::where('active', 1)
          ->where('destination', 'San Diego')
          ->update(['delayed' => 1]); // this will also update the record
Run Code Online (Sandbox Code Playgroud)

所以你甚至不应该将检索到的模型分配给任何变量.更新的属性作为参数传递.

Laravel文档中的示例和更多信息.


sob*_*han 12

在@ginopane讲述差异时,只有一件事没有说明,如果你在一个query builder resultlaravel 上使用update方法将忽略$fillable$guard模型的数组.如果要将Input::all()参数用作更新,这一点尤为重要:

Post::where('id', $id)->update(Input::all());
Run Code Online (Sandbox Code Playgroud)

因此,在这种情况下,如果您使用App\Flight::where('active', 1)->update(Input::all());数据库中的所有内容,即使您将其放入,也会更新$fillable.因此,请确保使用saveupdate方法Eloquent instance而不是查询构建器1.即使用户提交了您不希望在数据库表中插入或更新的字段,以下代码也会正常:

// User model
protected $fillable = ['email', 'name'];


// controller
public function update($id)
{
    $user = User::findOrFail($id);

    // validate the input here, use Request to do the job or whatever you like

    $user->update(Input::all());

    return view('some_view')->with('notice', 'user updated');
}
Run Code Online (Sandbox Code Playgroud)

现在,不管是什么在这里传递的形式,只nameemail将被更新.

希望这个完整的@ginopane回答


Ami*_*agh 9

save():您可以将其视为相当于 sql 中的 INSERT,它将创建一个新模型(并将其插入到数据库中)

要在数据库中创建新记录,请创建一个新模型实例,在模型上设置属性,然后调用 save 方法

update():您可以将其视为相当于 sql 中的 UPDATE,它将创建一个新模型(并将其插入到数据库中)

save 方法也可用于更新数据库中已存在的模型。要更新模型,您应该检索它,设置您希望更新的任何属性,然后调用 save 方法。同样,updated_at 时间戳会自动更新,因此无需手动设置其值

代码

    $flight = App\Flight::find(1);
    if (empty($flight)) {// you can do this condition to check if is empty
        $flight= new Flight;//then create new object
    }

    $flight->name = 'New Flight Name';

    $flight->save(); //this will UPDATE the record with id=1
Run Code Online (Sandbox Code Playgroud)

对于更详细的文档

  • 请尝试提供此类原因的解释并继续提问。 (3认同)