-3

I have a CustomObject and a User Object and both are not related to each other, however there is a field in both the object that stores same values. I have to use that field to compare and create map userId and CustomObject record.

Map<String, CustomObject> userIdCustomObject = new Map<String, CustomObject>();

There is a field called CustomObject.dob__c Below is the snippet :

public static void fetchDobOfUsers(List<User> userList){
        Map<String, CustomObject> userIdCustomObject = new Map<String, CustomObject>();
        Map<String, String> userIdDobMap = new Map<String, String>();
        for(user userRec : [SELECT Id, Name, dob__c FROM User WHERE Id IN: userList]) {
            userIdDobMap.put(userRec.Id, userRec.dob__c );
            CustomObject__c record = [SELECT Id, Name, dob__c FROM CustomObject__c WHERE dob__c = userRec.dob__c ];
            userIdCustomObject.put(userRec.Id, record);
        }
              
    }

I want to avoid the SOQL inside SOQL. Is there a better way achieve this?

3

1 Answer 1

1

I think something like this would work:

// Get a list of all user Dob__c so we don't have to query the whole CustomObject__c table
User[] usersToProcess = [SELECT Id, Name, Dob__c FROM User WHERE Id IN :userList];
String[] dobCollection = new String[]{};
for(user userRec : usersToProcess ) {
    if (!userRec.Dob__c.isBlank()) {
        dobCollection.add(userRec.Dob__c);
    } else {
        System.debug('Heads up, we\'re not going to process user ' + userRec.Id + ' because dob__c was blank. ');
    }
}

// Query the CustomObject__c table and store each record
Map<String, CustomObject__c> dobToObject = new Map<String, CustomObject__c>();
for (CustomObject__c obj : [SELECT Dob__c FROM CustomObject__c WHERE Dob__c IN :dobCollection]) {
    dobToObject.put(obj.Dob__c, obj);
}

// Finally, pair the CustomObject__c table with the user record and store it in a new map
Map<Id, CustomObject__c> userIdCustomObjectMap = new Map<String, CustomObject__c>();
for (User userRec : usersToProcess) {
    if (dobToObject.containsKey(userRec.Dob__c)) {
        CustomObject__c obj = dobToObject.get(userRec.Dob__c);
        userIdCustomObjectMap.put(userRec.Id, obj);
    } else {
        System.debug('Heads up, we don\'t have a match for dob__c ' + userRec.Dob__c);
    }
}
0

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