Relationship Queries in SOQL - Parent To Child

Relationship Queries in SOQL - Parent To Child

  • Relationship field contains at least two Objects -?a Child Object and a Parent Object.
  • These queries are used to fetch data from the Parent object when the query is written on the Child object or Child object when the query is written on the?Parent object.?

Parent To Child Relationship :

In Parent To Child relationship, we write an?Inner Query or Sub Query?in the Main Query to fetch the records of the Child.?

No alt text provided for this image

1.?Standard Object:-

  • In this relationship, a query will be written on?the Parent?object and we try to fetch the field(Records) of?the Child?object as well as?Parent?object together.
  • Let's take?Account as Parent Object and?Contact?as the Child object.
  • There is?a One-To-Many relationship between them and?a?Child Relationship Name?which helps to create a relationship between them.?

List<Account> accList = [ SELECT Name , NumberOfEmployees , (SELECT firstName , lastName , Phone FROM Contacts) FROM Account ];

  • Here?Name?and?NumberOfEmployee?are the fields of?the Account?object while?firstName, lastName, and Phone?are the field of?the Contact?object.?
  • So to fetch the field of the Child object we use?Inner Query/Sub Query?in the Main Query.
  • Here?Contacts?is Not the Object Name but the?Child Relationship Name?which is on Child Object.

2. Custom Object:-

  • In this relationship, the query will be written on?the Parent?object and we try to fetch the field of the child object as well as the Parent object.
  • Let's take?Student__c?as Parent Object and?Marks__c?as the Child object.
  • There is?a One-To-Many relationship between them and?a?Child Relationship Name?which helps to create a relationship between them.?

List<Student__C> stdList = [ SELECT Name, Email_ID__c, Roll_Number__c, Student_Address__c, (SELECT Name, Percentage_Marks__c, Total_Marks__c FROM Marks__r ) FROM Student__c ];

  • Here??Name, Email_ID__c, Roll_Number__c,?Student_Address__c?are the field of?Student__c?object while?Name, Percentage_Marks__c , Total_Marks__c?are the field of?Marks__c?object.
  • So to fetch the field of the Child object we use?Inner Query/Sub Query?in the Main Query.
  • Here?Marks?is Not the Object Name but the?Child Relationship Name?which is on Child Object.

?Note:-??In Custom Object,?Child Relationship Name?must be written with suffix?__r??while in Standard Object simply use the?Child Relationship Name.

Shivam Gupta

Salesforce Administrator & Developer | Salesforce Industries | 10x Salesforce Certified | Trailhead Double Ranger ????

2 年

A Student is a custom object, So your List definition must be "List<Student__c>"

要查看或添加评论,请登录

VINAY MADHAV???的更多文章

社区洞察

其他会员也浏览了