0 votes

I have a requirement to upsert parent records by External ID ExtParent__c field. And upsert child records by its External ID ExtChild__c field.

For this, I used:

upsert parentRecord ExtParent__c; //which inserts parent records

upsert childrecord ExtChild__c; // which inserts child records

Now, Is there a way to insert both these related records using single DML?

1 Answer

0 votes
Best answer

Assuming parent and child are the same sObject type (this is required for upsert), you can link the records as such:

mySObjectType[] records = new mySObjectType[] {
  new mySObjectType(Name='Parent',ExternalId__c='123'),
  new mySObjectType(Name='Child',ExternalId__c='456',Parent__r=new mySObjectType(ExternalId__c='123'))
upsert records mySobjectType.ExternalId__c;

If you're inserting or updating, you can use the same technique, even for different sObjects. However, there is a limitation on upsert that prevents you from mixing sObject types in the same list.

So, if the parent and child are the same type (e.g. Account), you can use upsert this way, but if the parent and child are of a different type, then you cannot specifically use upsert in a single DML statement. You would need two DML statements, or use either insert or update (e.g. creating the parent and child at once would be acceptable). The parent must be created earlier in the list than the child.

Welcome to Memory Exceeded, where you can ask questions and receive answers from other members of the community.