1

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.

1 Answer 1

4

You can create a list; the index of one will match the other, so you can relate them later:

List<CustomObject__c> COs = [Select Id, sf_Guardian_1__c, sf_Guardian_2__c,RelationshipRecordLookup__c from CustomObject__c Limit 1000];
    npe4__Relationship__c[] relationships = new npe4__Relationship__c[0];

for (CustomObject__c CO: COs)
{
    relationships.add(new npe4__Relationship__c(npe4__Contact__c = CO.sf_Guardian_1__c, npe4__RelatedContact__c = CO.sf_Guardian_2__c, npe4__Status__c = 'Current'));
}
insert relationships;
for(Integer index = 0, size = cos.size(); index < size; index++) {
    cos[index].RelationshipRecordLookup__c = relationships[index].Id;
}
update cos;
2
  • So you are saying that I can count on the List to maintain the order / index of the items. This will work great for me then. Thank You!
    – Joseph U.
    Commented Nov 2, 2016 at 23:23
  • @JosephU. Yes, the list will maintain the correct order for you.
    – sfdcfox
    Commented Nov 2, 2016 at 23:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .