0

I need an SOQL query to find all the fields in an Object which are referencing to other Objects. For Example

Account is an sObject which has different fields which refer to the other sObjects. The SOQL query should be such that all the related sObjects should be listed when we look for any sObject.

[Account] -> [Contact, AccountContactRole, Case, Asset, Contract, Order, Opportunity]

2
  • 1
    SOQL is not, IMHO, the right way to get this information. Instead you should be using the metadata API or the Apex Schema access.
    – Phil W
    Commented Feb 26, 2021 at 12:23
  • If the need is to show specifically the values of all the lookup fields, then you can use the metadata API or Schema class like Phil W suggested and use that to construct a dynamic query.
    – nbrown
    Commented Feb 26, 2021 at 13:58

1 Answer 1

1

I think SOQL query won't be able to provide for this instead use the Dynamic apex to find out about the lookup fields for the current object (Which is basically the fields on the current object pointing to other object) and then u can apply dynamic query on using all the lookup

String objectName = 'Opportunity';
String fieldName = 'AccountId';

SObjectType r = ((SObject)(Type.forName('Schema.'+objectName).newInstance())).getSObjectType();
DescribeSObjectResult d = r.getDescribe();
System.debug(d.fields
        .getMap()
        .get(fieldName)
        .getDescribe()
        .getType());

.getType() will provide the lookup fields with value "REFERENCE".

You must log in to answer this question.

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