在laravel中保存vs更新

时间:2016-04-27 07:57:32

标签: laravel-5

Laravel中 save() update()方法有什么区别。

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

3 个答案:

答案 0 :(得分:34)

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

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

 $flight = new Flight;

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

 $flight->save(); // it will INSERT a new record

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

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

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

$flight->save(); //this will UPDATE the record with id=1

使用update()方法可以更方便地更新模型:

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

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

Laravel's docs中的示例和更多信息。

答案 1 :(得分:9)

在@ginopane所说的差异中,只有一件事没有说明,如果你在query builder result使用更新方法,那么laravel会忽略$fillable或{{1你的模型的数组。如果您想使用$guard作为参数进行更新,这一点尤其重要:

Input::all()

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

Eloquent instance

现在,无论在此处传递的是什么内容,都只会更新// 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'); } name

希望这完整的@ginopane回答

答案 2 :(得分:-3)

尝试此代码

    $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