Wednesday, May 18, 2011

Salesforce - Get the list of all related objects from an object and their particular records

Solution : Lets get the records of all objects which are related to Account


List<Schema.SObjectType> childList = new List<Schema.SObjectType>();
Schema.DescribeSObjectResult R = Account.SObjectType.getDescribe();
//Create a list of child objects schema
for(Schema.ChildRelationship C : R.getChildRelationships()){
if(C.getRelationshipName()!=null && C.getRelationshipName().contains('__r')){
Schema.SObjectType child = C.getChildSObject();
System.debug('field****'+C.getField());
System.debug('field describe****'+C.getField().getDescribe());
System.debug('child****'+child);
childList.add(child);
}
}


//Querying all records
for(Schema.SObjectType objectToQuery : childList){
//Create dynamic query
String soqlQuery = 'SELECT Id,Name FROM '+objectToQuery;
System.debug('soqlQuery****'+soqlQuery);

//Execute query
List<SObject> results =  Database.query(soqlQuery);
System.debug('results****'+results);

No comments:

Post a Comment