Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent model mass update

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 Illuminate\Database\Eloquent\Model class to accomplish such a thing?

like image 330
papas-source Avatar asked Mar 15 '14 22:03

papas-source


2 Answers

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.

like image 140
bryceadams Avatar answered Oct 01 '22 19:10

bryceadams


For mass update/insert features, it was requested but Taylor Otwell (Laravel author) suggest that users should use Query Builder instead. https://github.com/laravel/framework/issues/1295

Your models should generally extend Illuminate\Database\Eloquent\Model. Then you access the entity iself, for example if you have this:

<?php Use Illuminate\Database\Eloquent\Model;  class User extends Model {      // table name defaults to "users" anyway, so this definition is only for     // demonstration on how you can set a custom one     protected $table = 'users';     // ... code omited ... 

Update #2

You have to resort to query builder. To cover table naming issue, you could get it dynamically via getTable() method. The only limitation of this is that you need your user class initialized before you can use this function. Your query would be as follows:

$userTable = (new User())->getTable(); DB::table($userTable)->where('age', '<', 18)->update(array('under_18' => 1)); 

This way your table name is controller in User model (as shown in the example above).

Update #1

Other way to do this (not efficient in your situation) would be:

$users = User::where('age', '<', 18)->get(); foreach ($users as $user) {     $user->field = value;     $user->save(); } 

This way the table name is kept in users class and your developers don't have to worry about it.

like image 27
phoops Avatar answered Oct 01 '22 17:10

phoops