Laravel 4: how to update multiple fields in an Eloquent model?

徘徊边缘 提交于 2019-12-21 03:12:32

问题


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, ...);

I can't just do:

$user->update($new_user_data);

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);

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.


回答1:


The method you're looking for is 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.




回答2:


You are looking for this:

$user = User::where("username","rok")
                ->update( 
                       array( 
                             "email" => "rok@rok.com",
                             "is_superuser" => 1,
                             // ..
                             )
                       );

Refer : http://laravel.com/docs/4.2/eloquent#insert-update-delete




回答3:


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.




回答4:


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)
);


来源:https://stackoverflow.com/questions/14878095/laravel-4-how-to-update-multiple-fields-in-an-eloquent-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!