2015-04-12 57 views
11

我對laravel很新,我試圖從表單的輸入更新記錄。但是我發現要更新記錄,首先需要從數據庫中獲取記錄。 是不是可以像更新記錄(設置主鍵):Laravel雄辯的更新記錄沒有從數據庫加載

$post = new Post(); 
$post->id = 3; //already exists in database. 
$post->title = "Updated title"; 
$post->save(); 

回答

12

您可以簡單地使用查詢生成器,而不是口若懸河,這個代碼直接在數據庫中更新數據:)這是一個示例:

DB::table('post') 
      ->where('id', 3) 
      ->update(['title' => "Updated Title"]); 

您可以檢查這裏的文檔的詳細信息:http://laravel.com/docs/5.0/queries#updates

+0

感謝百萬..你讓我的一天 –

+0

@KuHyeSun很高興它適合你!乾杯! –

+1

不,因爲這樣你就失去了你的時間戳和其他模型行爲 – malhal

0

首先你需要加載該行更新:

$post = Post::find($id); 

我你的情況

$post = Post::find(3); 
$post->title = "Updated title"; 
$post->save(); 
+3

他不想更新之前運行'select'查詢。 – harrrrrrry

+0

@zairwolf:這個答案沒有錯。這也是獲取記錄對象和更新特定字段的好方法。 –

+2

他想避免提取記錄。我來到這裏是因爲我有一個循環,我想更新一些行,我無法獲取記錄,它會太亂,最重要的是效率低下 – ggderas

14
Post::where('id',3)->update(['title'=>'Updated title']); 
+0

這是正確的答案。 –

0

您還可以使用firstOrCreate OR firstOrNew

// Retrieve the Post by the attributes, or create it if it doesn't exist... 
$post = Post::firstOrCreate(['id' => 3]); 
// OR 
// Retrieve the Post by the attributes, or instantiate a new instance... 
$post = Post::firstOrNew(['id' => 3]); 

// update record 
$post->title = "Updated title"; 
$post->save(); 

希望它會幫助你:)