Laravel ORM批量插入

时间:2019-06-09 07:56:02

标签: php eloquent laravel-5.8

我无法使用Model :: create($ mainArray)方法通过一个查询使用Laravel ORM插入多行

我尝试将多个数组放在一个主数组中,该数组要通过一个查询而不是foreach和多个查询插入数据库中。

我的$ mainArray看起来像这样:

    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
      ]

因此,当我尝试使用Model :: create()方法在foreach中一一插入时,这是可行的。但是,当我尝试Model :: create($ mainArray)时,我收到此错误消息:

  

ErrorException(E_WARNING)   preg_match()期望参数2为字符串,给定数组

1 个答案:

答案 0 :(得分:0)

更新:

在相关模型中,您可以使用saveMany/createMany方法进行多次插入。您可以使用可以接受属性数组的insert()方法。但是您需要手动更新created_at和Updated_at。

Model::insert($mainArray);