Okay, so basically what I'm trying to do, is gather Companies and Employees from an external API. For the purpose of this, I'll call the API objects:
- Companies = extCompanies
- Employees = extEmployees
In my database, I also have Companies and Employees. I'll name them
- Companies = intCompanies
- Employees = intEmployees
Basically, I need to sync the external data, with the internal.
I could just create each company with their respective employees in the loop, but that would result in an insane amount of queries being made.
- Hence why I settled on createMany. The only problem is that intEmployees needs to be "linked to" intCompanies (intCompanies->hasMany)
This is what happens right now:
$allExtCompanies = [];
foreach($extCompanies as $extCompany)
{
$allExtCompanies[] = [.. SOME data from $extCompany here ..];
}
$this->intCompanies->createMany($allExtCompanies);
And I simply need a way to also create intEmployees. I could create an array (like allExtCompanies) but I dont know the intCompanies database id's yet.
I decided to settle on:
$allExtCompanies = [];
$allExtEmployees = [];
foreach($extCompanies as $extCompany)
{
$allExtCompanies[] = [.. SOME data from $extCompany here ..];
foreach($extCompany->employees as $extEmployee)
{
$allExtEmployees[$extCompany->extId][] = [.. SOME data from $extEmployee ..];
}
}
$intCompanies = $this->intCompanies()->createMany($allExtCompanies);
foreach($intCompanies as $intCompany)
{
if(isset($allExtEmployees[$intCompany->extId]))
{
$intCompany->employees()->createMany($allExtEmployees[$intCompany->extId]);
}
}