如何在laravel中将数组插入数据库而不出错

我有一个 excel 文件,我从 excel 构建了一个数组,我需要将数组插入到 laravel 中的数据库中,但 laravel 有错误,我的数组是


private function InsertInDatabase(): void

{

    $insertableData = [

        ['name' => 'joe', 'card_type' => 'mastercard', 'balance' => 100 , 'last_ip'=> '122.154.1.5'],

        ['name' => 'sara', 'card_type' => 'visa', 'balance' => 10 , 'last_ip'=> '125.194.11.150'],

    ];

        

    $arrayCount = count($insertableData);


    for ( $l = 0; $l <= $arrayCount; $l++ )

    {


        

        Database::table($this->dbname)->insert(

            $insertableData[$l]

        );

        

            

    }

}

但有错误如何清除此错误


TypeError

Argument 1 passed to Illuminate\Database\Query\Builder::insert() must be of the type array, null given, called in C:\xampp\htdocs\xlsfile\app\Excel\ExcelToDatabase.php on line 99


泛舟湖上清波郎朗
浏览 171回答 4
4回答

隔江千里

尝试这样$data = [&nbsp; &nbsp; [...], [...]]foreach($data as $item) {&nbsp; &nbsp; &nbsp;YourModel::create($item); // YourModel::insert($item);&nbsp; &nbsp; &nbsp;//Database::table($this->dbname)->insert($item);}或批量插入YourModel::insert($data); <-- Eloquent// DB::table($this->dbname)->insert($data); <-- Query Builder

慕后森

$arraylist代码中没有变量。我想你的意思是$insertableData。如果是,则替换$arraylist为$insertableData.你实际上并不需要循环:$insertableData = [&nbsp; &nbsp; &nbsp; &nbsp; ['name' => 'joe', 'card_type' => 'mastercard', 'balance' => 100 , 'last_ip'=> '122.154.1.5'],&nbsp; &nbsp; &nbsp; &nbsp; ['name' => 'sara', 'card_type' => 'visa', 'balance' => 10 , 'last_ip'=> '125.194.11.150'],&nbsp; &nbsp; ];DB::table($this->dbname)->insert($insertableData);

明月笑刀无情

使用 Eloquent 或查询构建器在 Laravel 中进行批量插入非常容易。您可以使用以下方法。&nbsp;$data = [&nbsp; &nbsp; &nbsp; &nbsp; ['user_id'=>'Coder 1', 'subject_id'=> 4096],&nbsp; &nbsp; &nbsp; &nbsp; ['user_id'=>'Coder 2', 'subject_id'=> 2048],&nbsp; &nbsp; &nbsp; &nbsp; //...&nbsp; &nbsp; ];&nbsp; &nbsp; Model::insert($data); // Eloquent approach&nbsp; &nbsp; DB::table('table')->insert($data); // Query Builder approach

芜湖不芜

$arraylist[$l] 必须是 $insertableData[$l]或使用批量插入:模型::插入($insertableData);
打开App,查看更多内容
随时随地看视频慕课网APP