How to query dynamically all the related records or child of a parent using parentid If you take for Account , Case,Partners,Opportunity,Note & Attachments etc...
4 Answers
Suppose you have an Id in a variable recordId
.
First fetch a map of keyPrefixes to its related SObjectType,
Map<String,Schema.SobjectType> keys = new Map<String,Schema.SobjectType>();
Map<String,Schema.SobjectType> describe = Schema.getGlobalDescribe();
for(String s:describe.keyset())
keys.put(describe.get(s).getDescribe().getKeyPrefix(),describe.get(s));
Next, use your recordId to fetch the correct SObjectType and then fetch it's all children SObjectTypes.
Schema.SObjectType sobjectTypeObj = keys.get(recordId.substring(0,3));
Schema.DescribeSObjectResult obj = sobjectTypeObj.getDescribe();
for (Schema.ChildRelationship cr: obj.getChildRelationships())
{
system.debug('Child Object Name:'+cr.getChildSObject());
}
Once you have all the child names, its pretty easy to for a nested SOQL of parent and child objects, like Select Id, Name, (Select Id, Name from Contacts) from Account
-
1
Select Id, Name, (Select Id, Name from Contact) from Account
=>Select Id, Name, (Select Id, Name from Contacts) from Account
– benahmCommented Apr 6, 2017 at 14:26
You can query the related objects to the Account like this:
select (select Id from Cases),(select Id from Opportunities),(select Id from Notes),(select Id from Attachments) from Account
-
I don't want to write the child object names Eg: Opportunities,Notes,Attachments– AnuCommented Apr 6, 2017 at 9:41
-
Then why do you explicitly state that in your original question? Commented Apr 6, 2017 at 9:42
-
i just edited my question.i have taken the sample related objects in the question,there will be some more childs also,, (......so on means more related objects.)– AnuCommented Apr 6, 2017 at 9:46
The DescribeSObjectResult Class should help you here:
Schema.DescribeSObjectResult describe = Account.sObjectType.getDescribe();
for (Schema.ChildRelationship child : describe.getChildRelationships()){
//do your logic
}
-
,You are trying to show the related Objects,but the query is not about that.we have to show the related records of the parent using the parent id.– SatyaCommented Apr 6, 2017 at 9:58
If you want to retrieve all parents you need to use the describe the ParentId field.
Schema.DescribeFieldResult f = Schema.sObjectType.Attachment.fields.parentid;
System.debug('Relationship Name: ' + f.getRelationshipName());
for(Schema.SObjectType reference : f.getReferenceTo()) {
System.debug('Lookup reference object name: ' + reference.getDescribe().getName());
System.debug('Lookup reference object label: ' + reference.getDescribe().getLabel());
}
Code segment that you can use all the objects where it is referenced and then you create a dynamic SOQL. which can be used in Database.Query();
The answers is lited here.
Let me know if it resolves.