Getting child objects of parent object in Salesforce

Getting child objects of parent object in Salesforce

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()
		);
	
	}

}

SubQuery can be used to retrieve child or related records in Salesforce.

SOQL Query:

SELECT Name,
(SELECT Name, AccountId
From Contacts)
FROM Account 

Leave a Reply