Laravel 4:如何在Eloquent模型中更新多个字段? [英] Laravel 4: how to update multiple fields in an Eloquent model?
问题描述
如何在雄辩模型中更新多个字段?假设我是这样的:
How can I update multiple fields in an Eloquent model? Let's say I got it like this:
$user = User::where("username", "=", "rok");
然后我拥有所有这些模型参数:
And then I have all these model parameters:
$new_user_data = array("email" => "rok@rok.com", "is_superuser" => 1, ...);
我不能只是做
$user->update($new_user_data);
正确的方法是什么?我希望不要foreach
.
What's the proper way? I hope not a foreach
.
但是,以下方法确实有效.这是要走的路吗?
The following does work, however. Is this the way to go?
User::where("id", "=", $user->id)->update($new_user_data);
最后一个问题(除了笨拙)是,从对象上下文使用它时,更新的字段在$this
变量中不可见.
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.
推荐答案
您要查找的方法是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();
实际上,您可以执行$user->fill($new_user_data)->save();
,但是我发现单独的语句更易于阅读和调试.
Actually, you could do $user->fill($new_user_data)->save();
but I find the separate statements a little easier to read and debug.
这篇关于Laravel 4:如何在Eloquent模型中更新多个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!