Home > Enterprise >  Adding a column with the same value when inserting multiple rows with Model::insert()
Adding a column with the same value when inserting multiple rows with Model::insert()

Time:12-25

I have an array of data extracted from a CSV file and insert the data in to the DB with:

HistoricData::insert($csv->content);

The array being inserted looks something like this:

[
  {
    "timestamp": "1619138160000",
    "open": "51917.16",
    "close": "51846.89",
    "high": "51919",
    "low": "51804.44"
  },
  {
    "timestamp": "1619138100000",
    "open": "51954.86",
    "close": "51917.15",
    "high": "51954.86",
    "low": "51914.06"
  }]

However, I also want to add an extra column called "historic_data_group_id" and have it equal to 1 for every row being inserted.

Is there a way to do this without having to cycle through the array and adding that for every element before calling the model's insert method? In the real world application this array has many thousand elements and so I would prefer a more efficient way if possible.

CodePudding user response:

You can use array_map()

$csvContent = array_map(function($oneEntry){
    $oneEntry['historic_data_group_id'] = 1;
    return $oneEntry;
}, $csv->content);

but cycling through the array seems more readable

foreach ($csv->content as &$content) {
    $content['historic_data_group_id'] = 1;
}
// unset($content);

CodePudding user response:

your model HistoricData already has this column? if not yet create migration to add this column with default 1. In new inserts its work auto (no need change $csv)

  • Related