1

I have the following apex:

Schema.SObjectField field = doesNotMatter();
String fieldName = field+'';
//fieldName now holds "NameOfTheField"
Schema.DescribeFieldResult fieldResult = field.getDescribe();
String typeName = fieldResult.getType()+'';
//typeName now holds "REFERENCE"
List<Schema.sObjectType> res = fieldResult.getReferenceTo();
List<String> names = new List<String>();
for(Schema.sObjectType obj) {
   names.add(obj.getName());
}

Now I would like to query all the ids of all the records of objects whose names are in names list. How can I do that? I am not worried about the number of records returned, since I always can append LIMIT to the query.

I am just continuing this question.

Thank you.

  • Hey @yourbuddy, what do you need? What contains the names list? I understand that you have a list like names = new String[]{'Account','Opportunity'} and you want to get all the record ids of these objects, Did I understand good? – Torsen Nov 19 '18 at 15:31
  • @Torsen, I updated my question a little bit. Thank you. – yourbuddy Nov 19 '18 at 15:34
  • @Torsen, you got it right. – yourbuddy Nov 19 '18 at 15:34
  • before getting the records you have to select one value from the names list ¿Is it ok? – Torsen Nov 19 '18 at 15:38
  • 1
    You have to know that Salesforce has limits with the queries. You only can run 100 queries per execution. This limit affects that your name list has more than 100 items your code will throw an exception. Another limit is that you can only get 50k records for all the queries. How @david-reed answered you in the other post, your requirement doesn't look like to have sense. – Torsen Nov 19 '18 at 15:52
0

you can try something like that:

But I don't recommend you to use

public static Map<String,SObject[]> getSobjectsByName (String[] objectNames){
        Map<String,SObject[]> sobjectsByName = new Map<String,SObject>();
        for(String objectname : objectNames){
            sobjectsByName.put(objectname, Database.query('SELECT Id, Name FROM '+objectname));
        }

        return sobjectsByName;
    }
| improve this answer | |
  • Are you sure that there will be a Name field on an object? – yourbuddy Nov 19 '18 at 16:01
  • yes, I am sure. All the records have an Id and a name field. The name field could be could be an autonumber – Torsen Nov 19 '18 at 16:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.