ELOQUENT更新数据库与保存();
问题描述:
我在这里做错了什么?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”循环,因为我不知道需要更新哪些列。
答
在模型中设置可访问数组,然后使用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
在查看并设置属性之前,您是否确定自己拥有'$ user'中的用户记录?另外,你可以使用'User :: find($ user_id_update_user_details ['user_id'])',因为你只需要一条记录。 – 2013-03-11 12:27:01
我真的不会这样做,因为这有一些严重的安全问题。您应该在您的模型上定义可访问的属性,并且可以[mass assignment](http://laravel.com/docs/database/eloquent#mass-assignment)输入或手动选择每个属性。此外,我想你想查询'where('id')'或'find($ id)'而不是'where('user_id')',但我可能是错误的。 – vFragosop 2013-03-11 15:40:20