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
klaus maierklaus maier 

make query more efficient

Hello guys,

i wonder if there is a way to avoid the for loop and make the query more efficient. I still want to query the line items and get a set of account ids.
Is it possible to get a map like <parent.id, opportunityLineItem>  ?
public static Set<Id> runningMemberships (Date dateField){
        Set<Id> idSet = new Set<Id> ();

        List<OpportunityLineItem> oliList = [
            SELECT Id, Opportunity.AccountId
            FROM OpportunityLineItem
            WHERE Opportunity.IsWon = true
            AND Opportunity.start__c <= :dateField
            AND Opportunity.end__c >= :dateField
            AND family__c = 'membership''
            LIMIT 50000
        ];

        for (OpportunityLineItem oli : oliList) {
            idSet.add(oli.Opportunity.AccountId);
        }
        return idSet;
    }
Greetings,

Klaus
 
Kritika RajKritika Raj
Hi Klaus , 

I dont think that you could avoid the for loop as you need to get all the Account Id here. But if you want to return map which will have information about AccountId and all the Opportunity Line Item related to the corresponding AccountId , then you can try this code . Let me know if you have any doubt . If no doubt then , Please marks this as best answer if it resolves your query.
public static Map<Id,List<OpportunityLineItem>> runningMemberships (Date dateField) {
    
    Map<Id,List<OpportunityLineItem>> accWitholi = new List<Id,List<OpportunityLineItem>>();
    //This Map will store the AccountId and all the Opp Line Items related to it.
    /*Ex: {
    'accId1' : {'oli1' , 'oli2' , 'oli3'} ,
    'accId2' : {'oli1' , 'oli2'} , ...so on
         }
    */
    
    for(OpportunityLineItem oli : [SELECT Id, Opportunity.AccountId 
                                   FROM OpportunityLineItem 
                                   WHERE Opportunity.start__c <= :dateField 
                                   AND Opportunity.end__c >= :dateField 
                                   AND family__c = 'membership' LIMIT 50000]) 
    {
        if(!accWitholi.containsKey(oli.Opportunity.AccountId)) {
            accWitholi.put(oli.Opportunity.AccountId,new List<OpportunityLineItem>{oliList});
        }
        else {
            List<OpportunityLineItem> oliList = accWitholi.get(oli.Opportunity.AccountId);
            oliList.add(oli);
            accWitholi.put(oli.Opportunity.AccountId,oliList);
        }
    }
    
    return accWitholi;
}

 
klaus maierklaus maier
Thanks Kritika,

in that case, a set of ids should be the most efficient way for my future needs. Greetings Klaus