getChildRelationships() can be used to retrieve all the related or child objects of an object in Salesforce Apex.
Sample code:
Schema.DescribeSObjectResult objResult
= Account.SObjectType.getDescribe();
List < Schema.ChildRelationship > objRelationships
= objResult.getChildRelationships();
for (
Schema.ChildRelationship cr : objRelationships
) {
if (
String.isNotBlank(
cr.getRelationshipName()
)
) {
System.debug(
cr.getRelationshipName()
);
}
}
Sub–Query can be used to retrieve child or related records in Salesforce.
SOQL Query:
SELECT Name,
(SELECT Name, AccountId
From Contacts)
FROM Account