fr33jumper
fr33jumper

Reputation: 103

Laravel ORM bulk insert

I cannot insert multiple rows with Laravel ORM with one query using method Model::create($mainArray)

I have tried put multiple arrays in one main array which want to insert in database with one query, not with foreach and multiple queries.

My $mainArray looks like this:

    array:49 [▼
      0 => array:17 [▼
        "time" => "2019-06-09 07:00:00"
        "summary" => "Partly Cloudy"
        "icon" => "partly-cloudy-day"
        "precipIntensity" => 0
        "precipProbability" => 0
        "temperature" => 21.34
        "apparentTemperature" => 21.34
        "dewPoint" => 14.02
        "humidity" => 0.63
        "pressure" => 1024.32
        "windSpeed" => 2.72
        "windGust" => 7.77
        "windBearing" => 246
        "cloudCover" => 0.43
        "uvIndex" => 3
        "visibility" => 13.2
        "ozone" => 324.62
      ]
      1 => array:17 [▼
        "time" => "2019-06-09 08:00:00"
        "summary" => "Clear"
        "icon" => "clear-day"
        "precipIntensity" => 0
        "precipProbability" => 0
        "temperature" => 23.22
        "apparentTemperature" => 23.22
        "dewPoint" => 13.6
        "humidity" => 0.55
        "pressure" => 1024.09
        "windSpeed" => 0.87
        "windGust" => 7.69
        "windBearing" => 205
        "cloudCover" => 0.21
        "uvIndex" => 5
        "visibility" => 16.09
        "ozone" => 324
      ]

So when i try to insert one by one row in foreach with Model::create() method, that's working. But when i try to Model::create($mainArray) i got this error message:

ErrorException (E_WARNING) preg_match() expects parameter 2 to be string, array given

Upvotes: 0

Views: 6565

Answers (2)

Agung Kessawa
Agung Kessawa

Reputation: 563

if no model involved, maybe you can use this,

DB::table('tablename')->insert($mainArray);

Upvotes: 1

Al Amin Chayan
Al Amin Chayan

Reputation: 2500

UPDATE:

In related model you can use saveMany/createMany method for multiple insert. You can use insert() method that accepts an array of attributes. But you need to update created_at and updated_at manually.

Model::insert($mainArray);

Upvotes: 0

Related Questions