Last active
June 9, 2017 13:36
-
-
Save LasseRafn/5b3b945eddb7ff6193fb18dd1ed16cfb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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() ); |
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
@LasseRafn I hope that I have correctly understood your case.
I have used
insert()
becausecreateMany()
execute a query for each employee.Obviously this require to associate the company ID before.
This example cares only to insert new companies and new employees.
If you need a complete sync (create/update/delete) we can change it to fit your needs.
using "createMany"
Using "insert"