0

I have a text field called "references" that holds Id's of Other objects. Now, I want to get records that are in "references" by searching all the objects.

Map<Id, CustObj1__c> obj1Records = new Map<Id, CustObj1__c>([SELECT Id, OtherFields FROM CustObj1__c WHERE Id IN : references]);
Map<Id, CustObj2__c> obj2Records = new Map<Id, CustObj2__c>([SELECT Id, OtherFields FROM CustObj2__c WHERE Id IN : references]);
Map<Id, CustObj3__c> obj3Records = new Map<Id, CustObj3__c>([SELECT Id, OtherFields FROM CustObj3__c WHERE Id IN : references]);
Map<Id, CustObj4__c> obj4Records = new Map<Id, CustObj4__c>([SELECT Id, OtherFields FROM CustObj4__c WHERE Id IN : references]);

If the references contain Ids of type CustObj1__c only then I am simply wasting other three queries. So, I am thinking of checking the type of each id and making a map and only query when the size is greater than 0.

    Map<String, Set<Id>> objNameToIds = new Map<String, Set<Id>>();
    objNameToIds.put("CustObj1", new Set<Id>());
    objNameToIds.put("CustObj2", new Set<Id>());
    objNameToIds.put("CustObj3", new Set<Id>());
    ....
    for(Id recId : references) {
    String objName = recId.getSObjectType().getDescribe().getName();
    
    if(objName == "CustObj1") {
       objNameToIds.get("CustObj1").add(recId); 
    } else if (objName == "CustObj2") {
       objNameToIds.get("CustObj2").add(recId);
    } else if (objName == "CustObj3") {
       objNameToIds.get("CustObj3").add(recId);
    } else if (objName == "CUstObj10" {
       objNameToIds.get("CustObj10").add(recId);
    }
    }
    

//Now loop through map objNameToIds and if values size greater than 0 then do query.

Above if else solution is getting very big as I have lot of object to check for. So, need help on finding a pattern on how I can query different tables using a set of Ids (called references). This set of Ids contain different type of objects Id.

1
  • 1
    better: SObjectType sobjType = recId.getSObjectType(); - no need to use strings
    – cropredy
    Jun 25, 2021 at 14:46

1 Answer 1

2

Instead of assigning empty sets to each object and making checks on objects names, I suggest you trying this:

Map<String, Set<Id>> objNameToIds = new Map<String, Set<Id>>();

for(Id recId : references) {
    String objName = recId.getSObjectType().getDescribe().getName();
    
    if (!objNameToIds.containsKey(objName)) {
        objNameToIds.put(objName, new Set<Id>());
    }

    objNameToIds.get(objName).add(recId);
}
1
  • yes, that's what i will do later when I push the code. Thank you for replying and giving your time :)
    – lambad
    Jun 25, 2021 at 12:15

You must log in to answer this question.

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