0

In the below code, i am using nested for loops. Could some one guide how can i overcome using nested for loops.

global class batchclass implements Database.Batchable<sObject> {
    global final String Query;
    global Batchforchattertopics() {
        query = 'SELECT Id,createddate,parentId FROM feeditem where (Parent.Type = \'Case\')';
    }
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<feeditem> scope) {

        List<object__c> o = new List<object__c>();
        for (feeditem cs : scope) {
            for (TopicAssignment t : [select id, topic.name, EntityId from TopicAssignment WHERE EntityId IN = :cs.id]) {
                Object__c c = new Object__c();
                c.Name = 'Test';
                o.add(c);

            }
        }
        insert cfd;
    }
    global void finish(Database.BatchableContext BC) {
    }
}

1 Answer 1

1

Main approach is to avoid execution of SOQL for every FeedItem, but rather do it for all the FeedItems for single chunk. So, at first you collect all the feed item ids, and then query all topic assignments for them, and create records in loop.

Here is an example code:

global class batchclass implements Database.Batchable<sObject> {
    global Batchforchattertopics() {
    }
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator([SELECT Id, Createddate, ParentId 
                                         FROM FeedItem 
                                         WHERE Parent.Type = 'Case'
                                        ]
                                       );
    }

    global void execute(Database.BatchableContext BC, List<FeedItem> scope) {
        List<object__c> objects_to_insert = new List<object__c>();
        Set<Id> feeditem_ids = new Set<Id>();
        for (feeditem cs : scope) {
            feeditem_ids.add(cs.Id);
        }
        for (TopicAssignment t : [SELECT id, topic.name, EntityId 
                                  FROM TopicAssignment 
                                  WHERE EntityId IN :feeditem_ids]) {
            Object__c c = new Object__c();
            c.Name = 'Test';
            objects_to_insert.add(c);
        }
        insert objects_to_insert;
    }

    global void finish(Database.BatchableContext BC) {
    }
}

You must log in to answer this question.

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