1

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;

1 Answer 1

4

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
2
  • 1
    Hi thanks, are you also able to do this with a list? Or would that involve dml statements inside a loop? Commented Aug 13, 2019 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
    Commented Aug 13, 2019 at 12:59

You must log in to answer this question.

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