2013-03-11 71 views
0

我在這裏做錯了什麼?ELOQUENT更新數據庫與保存();

public static function updateuserdetails(){ 

    $user_id_update_user_details = Input::get(); 
    // find the user to update : 
    $user = User::where('user_id' , '=', $user_id_update_user_details['user_id'])->first() ; 

    foreach ($user_id_update_user_details as $key => $value) {   
     $user->$key = $value ; 
    } 

$affected = $user->save(); 
return $affected ; 
} 

它不會將數據保存到數據庫。我必須使用「foreach」循環,因爲我不知道需要更新哪些列。

+0

在查看並設置屬性之前,您是否確定自己擁有'$ user'中的用戶記錄?另外,你可以使用'User :: find($ user_id_update_user_details ['user_id'])',因爲你只需要一條記錄。 – 2013-03-11 12:27:01

+0

我真的不會這樣做,因爲這有一些嚴重的安全問題。您應該在您的模型上定義可訪問的屬性,並且可以[mass assignment](http://laravel.com/docs/database/eloquent#mass-assignment)輸入或手動選擇每個屬性。此外,我想你想查詢'where('id')'或'find($ id)'而不是'where('user_id')',但我可能是錯誤的。 – vFragosop 2013-03-11 15:40:20

回答

1

在模型中設置可訪問數組,然後使用fill來代替。另外...不是你的身份證叫'身份證'?如果這樣設置user_id的值可能會導致底層的SQL失敗。

class User extends Eloquent { 

    public static $accessible = array('id', 'name', 'email', ...); 

} 

Route::post('user/save', function() 
{ 
    $user = User::find(Input::get('id')); 

    if (empty($user)) 
     return 'Could not find user'; 

    $user->fill(Input::get()); 

    $user->save(); 
}); 
+0

它工作!非常感謝 – 2013-03-11 20:14:47