phparrayslaravelbuilder

How to Create a Incremental Array to Make a Bulk Insert?


I need to do something like the example below but I do not know how to add the field to the array.

    $column_count = 0;
    foreach ($line as $column) {

        $array_line[$column_count] = $field_names[$column_count] => $column;
        $column_count++;
    }
    DB::table('table')->insert($array_line);

When I tried to execute like this:

    $column_count = 0;
    foreach ($line as $column) {

        $array_line[$column_count] = [$field_names[$column_count] => $column;]
        $column_count++;
    }
    DB::table('table')->insert($array_line);

I get an error that shows me how Laravel set up my query and it looks like this:

    INSERT INTO table (column1) VALUES (value_original_column_1), (value_original_column_2), (value_original_column_3);

When te correct way should be:

    INSERT INTO table (column1, colum2, column3) VALUES (value_original_column_1, value_original_column_2, value_original_column_3);

Solution

  • $column_count = 0;
    $array_line =[];
    $line = ['column1','column2'];
    $field_names = [ 0 => "title",1=>"description"];
     foreach ($line as $column) {
       $array_line[$field_names[$column_count]] =   $column;
            $column_count++;
     }
    \DB::table('post')->insert($array_line);