Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Please correct me if I am wrong, but I think there is no such thing as mass update in an Eloquent model.

Is there a way to make a mass update on the DB table without issuing a query for every row?

For example, is there a static method, something like

User::updateWhere(
    array('age', '<', '18'),
    array(
        'under_18' => 1 
        [, ...]
    )
);

(yes, it is a silly example but you get the picture...)

Why isn't there such a feature implemented? Am I the only one who would be very happy if something like this comes up?

I (the developers), wouldn't like to implement it like:

DB::table('users')->where('age', '<', '18')->update(array('under_18' => 1));

because as the project grows, we may require the programmers to change the table name in the future and they cannot search and replace for the table name!

Is there such a static method to perform this operation? And if there is not, can we extend the IlluminateDatabaseEloquentModel class to accomplish such a thing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
328 views
Welcome To Ask or Share your Answers For Others

1 Answer

Perhaps this was not possible a few years ago but in recent versions of Laravel you can definitely do:

User::where('age', '<', 18)->update(['under_18' => 1]);

Worth noting that you need the where method before calling update.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...