Relationship Query in Apex Salesforce

by Rijwan Mohmmed
0 comment
relationship-query-in-apex-salesforce

Hello friends, Today we will discuss Relationship Query in Apex Salesforce. Usually, we need to retrieve the list of all child records related to a parent record in SOQL if there is a relationship between the objects (master-detail OR lookup). In Salesforce, you can do this by using a relationship query.

In order to use a relationship query, it is essential to know the name of the relationship between the two objects. You can obtain this relationship name by going to the Master-detail or Look-up fields on child objects.

Parent-to-child query in salesforce using the inner query :

Parents and children have unique names for their relationships, which is the plural of the name of the child object. The Account object has child relationships to Assets, Cases, and Contacts, and has a relationship name for each. These relationships can be traversed only in the SELECT clause, using nested SOQL queries.

For Standard Object: For standard object relationship, select the lookup field, and you can check child relationship name.

Account acc = [Select Name, (Select Id, FirstName from Opportunities) from account where id = ‘XXXX’];
System.debug('Account details' + acc);
System.debug('Account Opportunities' + acc.Opportunities);

For Custom Object: For custom object relationship, select the lookup field, and you can check child relationship name. Here we need to put __r at the end of object name.

Account acc = [Select Name, (Select Id, Name FROM Jobs__r) from account where id = ‘XXXX’];
System.debug('Account details' + acc);
System.debug('Account Jobs' + acc.Jobs__r);

Child-to-parent query in salesforce :

Here we retrieve the parent fields values by child query

For Standard Object: For standard object fields we can direct use the object name in SOQL query to access parent object fields by child object query.

Contact con = [SELECT Id, AccountId, Account.Name FROM Contact WHERE Id ='XXXXX'];
System.debug('Account Name ==> ' + con.AccountId);
System.debug('Account Name ==> ' + con.Account.Name);

For Custom Object: For custom object relationship, we need to put __r at the end of the object name. Below is Contact is child object and Job is parent Object.

Contact con = [SELECT Id, Job__r.Id, Job__r.Name FROM Contact WHERE Id ='XXXXX'];
System.debug('Job Id ==> ' + con.Job__r.Id);
System.debug('Job Name ==> ' + con.Job__r.Name);

You may also like

Leave a Comment