Eloquent model mass update

前端 未结 7 1679
长发绾君心
长发绾君心 2020-12-03 00:41

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

7条回答
  •  臣服心动
    2020-12-03 01:21

    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:

    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.

提交回复
热议问题