function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
AlteryxMikeAlteryxMike 

Need help with batchable class syntax for relationships

I am new to force.com and apex and am coding up a batch class to copy records from the Opportunity object into a custom object.

Everything is working well except I can't figure out how to access fields in a relationship to Opportunity such as Account.Name.

 

For example, I am using a query such as this in my batch class start method:

 

    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator('SELECT o.Amount, o.Account.Name from Opportunity o');
    }

 

Then in my execute method, I am accessing the values like this:

 

    global void execute(Database.BatchableContext BC, list<sObject> scope){
        List<OpportunityTrend__c> opps = new List<OpportunityTrend__c>();

        for (sObject s : scope) {

            OpportunityTrend__c OpTrend = new OpportunityTrend__c();

            OpTrend.Amount__c = (Decimal)s.get('Amount');

            opps.add(OpTrend);

        }

        insert opps;

    }

 

Where I need help is in the syntax to get at the o.Account.Name field string value.

I've tried this, but it doesn't work:

 

        OpTrend.AccountName__c = (String)s.get('Account.Name');

 

I'm not sure if my problem is in my s.get() call (wrong syntax, wrong method, etc) or if it's in my initial SOQL query.

 

 

Any help would be greatly appreciated.

BTW, I have looked at this thread: SOQL-Getting-Opportunity-AccountName-in-one-query which appears to be very similar to the question I have, but does not provide the level of detail I need.

 

Thanks!!

 

-mike

 

Best Answer chosen by Admin (Salesforce Developers) 
ShamilShamil

Use 

String.valueOf(c.getSObject('Account').get('Name'));

All Answers

ShamilShamil

Use 

String.valueOf(c.getSObject('Account').get('Name'));
This was selected as the best answer
AlteryxMikeAlteryxMike

Can't thank you enough for this. Works great.

Thanks for helping me get on my feet - now that I see the answer, it totally makes sense.

 

thanks again!

 

-mike