Laravel 4:如何更新 Eloquent 模型中的多个字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14878095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 4: how to update multiple fields in an Eloquent model?
提问by duality_
How can I update multiple fields in an Eloquent model? Let's say I got it like this:
如何更新 Eloquent 模型中的多个字段?假设我是这样得到的:
$user = User::where("username", "=", "rok");
And then I have all these model parameters:
然后我有所有这些模型参数:
$new_user_data = array("email" => "[email protected]", "is_superuser" => 1, ...);
I can't just do:
我不能只做:
$user->update($new_user_data);
What's the proper way? I hope not a foreach
.
什么是正确的方法?我希望不是foreach
.
The following does work, however. Is this the way to go?
但是,以下确实有效。这是要走的路吗?
User::where("id", "=", $user->id)->update($new_user_data);
The problem with the last one (besides it being clunky) is that when using it from an object context, the updated fields are not visible in the $this
variable.
最后一个(除了笨重)的问题在于,当从对象上下文使用它时,更新的字段在$this
变量中不可见。
回答by J.T. Grimes
The method you're looking for is fill()
:
您正在寻找的方法是fill()
:
$user = User::where ("username","rok"); // note that this shortcut is available if the comparison is =
$new_user_data = array(...);
$user->fill($new_user_data);
$user->save();
Actually, you could do $user->fill($new_user_data)->save();
but I find the separate statements a little easier to read and debug.
实际上,您可以这样做,$user->fill($new_user_data)->save();
但我发现单独的语句更易于阅读和调试。
回答by Kumar Ramalingam
You are looking for this:
你正在寻找这个:
$user = User::where("username","rok")
->update(
array(
"email" => "[email protected]",
"is_superuser" => 1,
// ..
)
);
Refer : http://laravel.com/docs/4.2/eloquent#insert-update-delete
参考:http: //laravel.com/docs/4.2/eloquent#insert-update-delete
回答by Alejo Toro
I should suggest to use shorter code, such as
我应该建议使用较短的代码,例如
$new_user_data=array('a'=>'n','b'=>'m');
$user=User::whereUsername('rok');//camelCase replaces "=" sign
$user->fill($new_user_data)->save();
Or even shorter
甚至更短
$new_user_data=array('a'=>'n','b'=>'m');
User::whereUsername('rok')->update($new_user_data);//camelCase replaces "=" sign
I believe the last statement is easier to debug and looks nicer.
Warning: If your table contains many users named 'rok' both mentioned statements will update all those registers at once. You should always update registers with the id field value.
我相信最后一条语句更容易调试并且看起来更好。
警告:如果您的表包含许多名为 'rok' 的用户,上述两个语句将立即更新所有这些寄存器。您应该始终使用 id 字段值更新寄存器。
回答by idro2k
Try this,
尝试这个,
// took required data out of the request
$postData = request(
[
'firstName',
'lastName',
'address1',
'address2',
'address3',
'postcode',
'phone',
'imageURL',
]
);
// persisted it to the database
DB::table('users')
->where('id', auth()->user()->id)
);