Relationships in Apex
Relationships in Apex
Using the relationships, we can retrive the related Objects data using the SOQL query.
Relationship name = Account
Child to parent Relationship
In the child -to-parent Relationship, we can query on Contact and retrieves the values from Account that is associated.
Contact C = [Select First Name, LastName, Account.Name, Account.Industry from Contact where id = 'XXXXX'];
System.debug (c. Account .Name); --->Prints the Account Name of Contact
System.debug (C. Account. Industry); ---> Prints the industry field value from account
Parent to child relationship
In the parent-to-child relationship. We can query on the parent object and we will get the details about child records.
Account a = [Select Name, (Select Contact .FirstName, contact .LastName from Account. Contacts) From Account where id ='xxxxxxx']
System debug (a); àthis will give all the Contact for that account
For (Contact C: a.Contacts)
system.debug (C. First Name);
This statement displays FirstName of all contacts that are associated with the account.When we want to write query on parent to child relationship then we need to write subquery ( query within another query)
Enthusiastic about exploring the skill set of Salesforce?Then, have a look at the Salesforce Training Online to gather additional knowledge.
This selection explains how relationship names for Custom objects and Custom fields that are created and used
|*When we use a relationship name in||a query. We must use the relationship|
|names without __c.||instead, append an||---r(underscore underscore r).|
|Relationship Name =Mother -of-child---||r, child -to-parent Relationship.|
parent-to-child Relationship, Relationship =Daughter--r
When we use a child-to-parent relationship.
EX:- Daughter_ _c D= [Select id, First name _ _C, Mother-of child_ _r.firstname from daughter where LastName_ _C LIKE 'C%']
The above query returns the ID and first name of daughter objects, and the first name of the daughter's mother if the mother’s last Name begins with 'C'
EX:- SELECT LastName __c, (Select LastName__c From Daughters --r) FROM mother- of-child __c.
The above query returns the Last name of all mothers, and for each mother returned, the last name of the mother's daughters.