2016-04-27 81 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答案