简体   繁体   中英

Laravel Eloquent Insert Multiple records only if one field is provided as an array

Does Laravel / Eloquent provide a way to create multiple records with one call, if only one field is provided as an array?

For example I got $request coming in with data below, but only propIds will be exploded and provided as an array, all other values will be the same for the all new records.

{"_token": "kEKmrPzu4nCk35xJAMOgdl0kNdwUZvpECsBl91dH",
"propIds": "126,129,71,82,77,64,69",
"rate": "4",
"cost": "55"
}

I could do a foreach and build an array and then run Model::insert($newArray); But maybe Laravel does provide a solution for if only one field is provided as an array. Thanks.

For now I am just using foreach loop to create array and then call Model::insert($newArray);

Inserting multiple records with Model::insert($newArray); will not automatically add created_at and updated_at dates . I added a timestamp as default value in the database.

Yes, it's possible. You need to use insert() and create a new array with this format:

Model::insert([
    ['prop_id' => 126, 'rate' => 4, 'cost' => 55],
    ['prop_id' => 129, 'rate' => 4, 'cost' => 55],
    ['prop_id' => 71, 'rate' => 4, 'cost' => 55],
]);

insert() will create just one DB query.

You can override Laravel Models create function like below :

Model

namespace App\Models;

class YourModel extends BaseModel
{
  protected $fillable = [
    "_token", "propId", "rate", "cost"
  ];

  // override
  public static function create(array $attributes = [])
  {
    $propIds = array_explode(',', $attributes['propIds']);

    foreach ($propIds as $key => $value) {        
      $model = new static([
        "_token"  => $attributes['_token'],
        "propId"  => $value,
        "rate"    => $attributes['rate'],
        "cost"    => $attributes['cost']
      ]);

      $model->save();
    }
  }
}

Controller

YourModel::create([
   "_token"  => $request->input('_token'),
   "propIds" => $request->input('propIds'), // "126,129,71,82,77,64,69"
   "rate"    => $request->input('rate'),
   "cost"    => $request->input('cost'),
]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM