I have some code that will loop through records and for each record create a new related record (that will serve as a parent records via a lookup field).
The challenge is that I then want to update a lookup field with the related object but I want to do it via a bulkified process.
Here is a non-bulkified way to do it through poor coding practices (because I am putting the insert inside of the for loop).
List<CustomObject__c> COs = [Select Id, sf_Guardian_1__c, sf_Guardian_2__c,RelationshipRecordLookup__c from CustomObject__c Limit 1000];
for (CustomObject__c CO: COs)
{
npe4__Relationship__c Relationship = new npe4__Relationship__c();
Relationship.npe4__Contact__c = CO.sf_Guardian_1__c;
Relationship.npe4__RelatedContact__c = CO.sf_Guardian_2__c;
Relationship.npe4__Status__c = 'Current';
Insert Relationship;
CO.RelationshipRecordLookup__c = Relationship.Id;
}
Update COs;
The biggest concern for me with this method is that since the Insert is in the Loop I will run out of SOQL calls.
To bulkify this I know instead of an insert the Relationship instance will be added to a list and that list will be inserted after the loop has completed. But then I no longer have a way (that I can think of) to grab the ID of the inserted Relationship record and add it to the matching CO record lookup field.
But I am at a loss on the proper steps to bulkify this process.