Skip to content

Instantly share code, notes, and snippets.

@LasseRafn
Last active June 9, 2017 13:36
Show Gist options
  • Save LasseRafn/5b3b945eddb7ff6193fb18dd1ed16cfb to your computer and use it in GitHub Desktop.
Save LasseRafn/5b3b945eddb7ff6193fb18dd1ed16cfb to your computer and use it in GitHub Desktop.
<?php
/*
* Various of other things going on up here. I slimmed down the code for readability,
* and focus. $companies is an array of .. companies .. gathered from an external API.
*/
$companiesToCreate = collect([]);
foreach ( $companies as $company )
{
$companiesToCreate->push( [...] ); /* Pushing some data from $company here */
foreach( $company->contacts()->all() as $contact)
{
/*
* I need to fetch contacts from $company and add that to the createMany below.
* Basically the best would be if I could just add it to the above push statement,
* with a array-key with the name of the hasMany-relation-method in the class.
* But I dont assume thats an option. With the current setup, I'll likely have to
* Create each company in the foreach, and append contacts to them in the loop too.
* Which is not really optimal, considering some companies might have 50.000 contacts,
* and that theres easily 5.000 companies in a single array. Likely more.
*/
}
}
$this->companies()->createMany( $companiesToCreate->toArray() );
@LasseRafn
Copy link
Author

Didn't even reply to the comment. Went back to this (at random) and remembered that your solution fixed this. Thanks so much!! 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment