
Relationship Queries in SOQL | Salesforce Tutorial Guide
Relationship field contains at least 2 Objects i.e a Child Object and a Parent Object.
These queries are used to fetch Data either from the Parent object when the query is written on Child object or Child object when the query is written on Parent object.
Child to Parent Relationship:
1. Standard Object:-
In this relationship, query will be written on the Child object and we try to fetch the field of the child object as well as the parent object.
Don't forget to check out: All You Need to Know About SOQL in Salesforce
Let's take Account as Parent Object and Contact as a Child object. There is a One-To-Many relationship between them and there is a Reference field in the child object which help to create a relationship between them.
List<Contact> conList = [SELECT firstName, lastName, Email, Account.Name, Account.NumberOfEmployees FROM Contact];
Here firstName, lastName, Email are the field of the Contact object while Name and NumberOfEmployee are the fields of the Account objects.
So to fetch the field of the Parent object we use the DOT NOTATION Method with the help of the parent object reference which is the Relationship Field name on the Child object.
Here Account is Not the Parent Object Name but the Relationship Field Name which is on the Child Object.
2. Custom Object:-
In this relationship, a query will be written on the Child object and we try to fetch the field of the child object as well as the parent object.
Let's take Consultant as Parent Object and Leave_Request as a Child object. There is a One-To-Many relationship between them and there is a Reference field in the child object which help to create a relationship between them.
List<Leave_Request__c> lrList = [SELECT Name, Leave_Status__c, Consultant__r.Name, Consultant__r.Consultant_Email__c, Consultant__r.Type__c, ];
Here Name, Leave_Status__c is the field of the Leave_Request object while Name, Consultant_Email__c, and Type__c are the field of the Consultant object.
Check out an amazing Salesforce video tutorial here: Parent to Child SOQL vs Map | Salesforce Training in Apex
So to fetch the field of the Parent object we use the DOT NOTATION Method with the help of the parent object reference which is the Relationship Field name on the Child object.
Here Consultant__r is Not the Parent Object Name but the Relationship Field Name which is on the Child Object.
Note:- In Custom Object, reference field name must be written with suffix __r after Reference Field Name while in Standard Object simply use the Reference Field Name.
Reference: shreysharma
Responses