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
Prachi SPrachi S 

Obtain Sobject relationship field dynamically

Hello Trailblazers, 
I have a requirement to develop object-agnostic apex class (i.e this class should be reusable across any salesforce objects) which fetches all child records related to a parent object. As you can see in the snippet below, my method accepts parent record ID and child object API name as input parameters. While I was able to make the method largely generic, I am stuck at finding a way to get relationship field dynamically. 
For E.g If the parent Object is Account and child object is Opportunity, to get all related opportunity for input account I would have to use AccountID relationship field in the query. 
However if the parent Object changes to Contact and child object changes to case below query wont work because the relationship field "AccountID" is hardcoded. Is there any way to make this ralationship field dynamic?
String queryStr ='select id, Name from ' + childObjAPIName + ' WHERE AccountID = :parentId' ;
    public static List<SObject> getMeChildRecords(Id parentId, String childObjAPIName){
        try {
            List<SObject> childRecordsList = new List<SObject>();
            //Get parent object API Name from input ID
            Schema.SObjectType parentObjAPIName = parentId.getsobjecttype();
            System.debug('I am the parent ' +parentObjAPIName);

            String queryStr ='select id, Name from ' + childObjAPIName + ' WHERE AccountID = :parentId' ;
            system.debug('my query: ' +queryStr);
            childRecordsList = Database.query(queryStr);
            return childRecordsList;   
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
Thanks for your help in advance!