简体   繁体   中英

Laravel Eloquent - Inserting multiple objects at once

I'm creating multiple (sometimes hundreds, sometimes thousands) Eloquent objects by reading a CSV file.

Take this loop for instance:

$cities = [];
while ($city = readNextCity()) {
  $cities[] = $city;
}
// ok how do I save all $cities without calling $city->save() on each?

We know that inserting multiple rows in one query is much more efficient than inserting 1 row per query. However, is there a way to insert multiple eloquent objects at once so that they get translated to one query? (If not, I don't mind writing it, but I don't want to duplicate efforts).

I think you can use the query builder for this.

$cities = array();
$i=0;
while ($city = readNextCity()) {
  $cities[$i++] = array('city' => $city);
}

DB::table('city')->insert($cities);

Hope this will help.

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