I want to create bulk insert data in my project, I’m using MariaDB / MySQL and laravel as a PHP framework. Actually, I can do something like this in my case
$data = [
['name' => 'Joh Doe', 'code' => '1234'],
['name' => 'Mr Lorem', 'code' => '5678'],
['name' => 'Mr Ipsum', 'code' => '9012'],
//...
];
MyTable::insert($data);
But, the problem is, I don’t just insert the data into 1 table, there are 5 tables that I have to enter data from and all of these tables are related to 1 main table. Here’s the single insert code that I made.
$myPost = MyTable::create(['name' => 'Joh Doe', 'code' => '1234']);
$myPost->ownedCar()->create([
'merk' => 'defaultMerk',
'qty' => 1,
'fuel' => 'gasoline'
]);
$myPost->ownedBike()->create([
'merk' => 'defaultMerk',
'qty' => 1,
]);
$myPost->ownedBicycle()->create([
'merk' => 'defaultMerk',
'wheel' => 2
'qty' => 1,
]);
$myPost->moneyOwned()->create([
'currency' => 'USD',
'value' => '696969',
]);
Okay, that is the single insert that I made. And here’s the bulk version that I made using a loop (LOL hahaha)
// let says $datas is form request
foreach($datas as $data) {
$myPost = MyTable::create(['name' => $data['name'], 'code' => $data['code']]);
$myPost->ownedCar()->create([
'merk' => 'defaultMerk',
'qty' => 1,
'fuel' => 'gasoline'
]);
//....
}
Okay, maybe there is no something wrong with my loop (I guess haha), but, what if the data that I insert to the form is more than 10k? or maybe 1k, it will take so long. So, there is the best way to solve this kind of issue? thanks