0

quick question here that's in the title. Is there any way to update the relationship record field in apex without looping through that object after querying a list of ids.

Example snippet below that currently is not working:

Opportunity o = [Select Id, lookup__r.field__c, lookup__r.field2__c from Opportunity];

o.lookup__r.field__c = 'test';
o.lookup__r.field2__c ++;

update o;
2

Yes,You can do that. You need an additional DML statement. You need to do like this:-

Opportunity o = [Select Id, lookup__r.field__c, lookup__r.field2__c from Opportunity];

o.lookup__r.field__c = 'test';
o.lookup__r.field2__c ++;

update o; //it will update opportunity

update o.lookup__r; //it will update the relationship record
  • 1
    Hi thanks, are you also able to do this with a list? Or would that involve dml statements inside a loop? – Alexander Atkinsoon Aug 13 '19 at 8:59
  • 1
    @AlexanderAtkinsoon You can add the __r values to a list<sobject> and update them at the end of the loop. – sfdcfox Aug 13 '19 at 12:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.