1

Can we write a join query and pass on to a batch handler. Once I get all the rows, I want to dynamically fetch values using their fields described from the rows containing info of both the objects.

Can this be done in some standard way or should I make it work having checks, hardcoded variables to validate and fetch results.

2
  • Can you please provide more information around the data model that you're referring to in your question? Also what are you trying to achieve? Some code snippets will be also greatly appreciated Commented Aug 18, 2014 at 5:26
  • I have two objects A and B. B has a lookup on A. I want to fetch all the rows of A and B using join in batches, process the fields dynamically using objectName.get(fieldName) in my execute method.
    – Ashu NCS
    Commented Aug 18, 2014 at 5:31

1 Answer 1

2

You can go from the parent and get the children using a nested SOQL query:

global class YourBatch implements Database.Batchable<sObject>
{
    String query;

    global YourBatch()
    {
        // Get evey record from object A and it's related records from object B
        query = 'SELECT Id, Name, (SELECT Id, Name FROM CustomObjectB__r) FROM CustomObjectA__c WHERE YourWhereClauseOnobjectA';
    }

    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<sObject> scope)
    {
        // Traverse through the Object A records
        for (sObject sObjectA : scope)
        {
            system.debug((String)sObjectA.get('Name'));

            if (sObjectA.getSObjects('CustomObjectB__r') != null)
            {
                // Traverse through Object B records only related to the current Object A record
                for (sObject sObjectB : (List <sObject>)sObjectA.getSObjects('CustomObjectB__r'))
                {
                    system.debug((String)sObjectB.get('Name'));
                }
            }
        }
    }

    global void finish(Database.BatchableContext BC)
    {
        // Do something
    }
}

Or alternatively you can query the children and get the fields from the parent:

Query:

query = 'SELECT Id, Name, CustomObjectA__r.Name, CustomObjectA__r.OtherField__c FROM CustomObjectB__c WHERE YourWhereClauseOnobjectB';

Execute:

// Traverse through the Object B records
for (sObject sObjectB : scope)
{
    system.debug((String)sObjectB.get('Name'));
    system.debug((String)sObjectB.get('CustomObjectA__r').get('OtherField__c'));
}
1
  • Thank you Bachovski. I used the first option and it works fine :)
    – Ashu NCS
    Commented Aug 18, 2014 at 7:47

You must log in to answer this question.

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