Skip to content

Instantly share code, notes, and snippets.

@LasseRafn
Created December 5, 2016 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LasseRafn/c0f33bce65cb412ecec2e0b0bd4c4970 to your computer and use it in GitHub Desktop.
Save LasseRafn/c0f33bce65cb412ecec2e0b0bd4c4970 to your computer and use it in GitHub Desktop.

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]);
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment