Query Five Levels Of Parents-to-Child Relationships in SOQL Queries
Conclusion:
If you are a developer working at Salesforce, you are likely familiar with the Powerful SOQL(Salesforce Object Query Language) tool. SOQL enables you to retrieve data from Salesforce various Objects, including parent and child objects.
Parents- to- Child Relationships:
Create a custom Object named “Employee”. Create Salary, Lookup(Account)fields on Employee Objects. Create a total Salary field on Account. Now Query Accounts Create this Year along With related Employees on account.
public class Mytest {
public static void countTotalSalary(){
List<Account>accWithEmployees=[SELECT Id,Total_Salary_c,(SEWLECT_c FROM Employees_r) FROM Account WHERE CreatedDate=THIS_YEAR];
if(accWithEmployees.isEmpty()){
for(Account acc:accWithEmployees){
Decimal TotalSal=0;
for(Employee_c emp :acc.Employees_r){
TotalSal=TotalSal+emp.Salary_c;
}
acc.Total_Salary_c=TotalSal;
}
}
if(accWithEmployees.isEmpty()){
update accWithEmployees;}}
Query Child-to-Parent Relationships:
Query Employees Created this week and if Phone is not populated on Employee record then copy Phone Of Related Account.
public class Mydemo {
public static void CopyAccountPhoneToContact(){
List<Contact>ContactHistory=[SELECT Id,FirstName,Phone,Account.Phone FROM Contact WHERE AccountId !=NULL];
if(ConHistory.isEmpty()){
For(Contact Con:ConHistory){
if(Con.Phone==null){
Con.Phone=Con.Account.Phone;
}
}
}
if(ConHistory.isEmpty()){
update ConHistory
}
}
}