2016-04-27 78 views
7

save()update()在Laravel中的方法有什么区别。保存和更新laravel

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

回答

17

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

$flight = new Flight; 

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

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

此外,它可以像一个UPDATE,当你的模型数据库中已存在:

在创建这是目前在数据库表中没有提出一个新的模型save()方法perfroms为INSERT 。所以,你可以得到的模型,修改某些属性,然后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

4

@ginopane告诉我的差异只有一点,那就是如果你在query builder result上使用更新方法,那么laravel会忽略你模型的$fillable$guard数组。如果你想使用Input::all()作为参数进行更新,这一点尤其重要:

Post::where('id', $id)->update(Input::all()); 

因此,在这种情况下,如果你使用App\Flight::where('active', 1)->update(Input::all());一切都在你的数据库将被更新,即使你把它放在$fillable。因此,请务必在Eloquent instance上使用saveupdate方法,而不要使用查询构建器之一。下面的代码将被罚款,即使用户在DATABSE表提交您不想插入字段或更新:

// 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'); 
} 

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

希望这个完整的@ginopane答案