+ Start a Discussion
KiranNaiduKiranNaidu 

Triggers : [SELECT Id,Name,(SELECT Id,Name FROM Opportunities) FROM Account WHERE Id IN :Trigger.New]);

Hi All,
I am learning the salesforce and wanted to understand the below which in the Trigger concept.

I get the below result
Code: [SELECT Id,Name,(SELECT Id,Name FROM Opportunities) FROM Account WHERE Id IN :Trigger.New]);
output: {0012w00000CWweoAAD=Account:{Id=0012w00000CWweoAAD, Name=Grapes & Melons}}

and then I tried accessing the Opportunities by useing the below code line
Code:
System.debug('acctsWithOpps.get(a.Id).Opportunities.size()=' + acctsWithOpps.get(a.Id).Opportunities);

output:
acctsWithOpps.get(a.Id).Opportunities.size()=(Opportunity:{AccountId=0012w00000CWweoAAD, Id=0062w000004b2mCAAQ, Name=Grapes & Melons Opportunity}, Opportunity:{AccountId=0012w00000CWweoAAD, Id=0062w000004b2mMAAQ, Name=Grapes & Melons Opty}, Opportunity:{AccountId=0012w00000CWweoAAD, Id=0062w000004b44SAAQ, Name=Grapes & Melons Opportunity})

How do i need to write the code to access each opportunity field details if i wanted to access. Let say I wanted to check a particular type of opportunity is existed or not and then do an operation.

Thank you!
Best Answer chosen by KiranNaidu
Danish HodaDanish Hoda
Hi Kiran,
You can have the code like this:
List<Account> acctsWithOpps = [SELECT Id,Name,(SELECT Id,Name FROM Opportunities) FROM Account WHERE Id IN :Trigger.New]);
for(Account acc : acctsWithOpps){
  if(!acc.Opportunities.isEmpty()){
     for(Opporutnity opty : acc.Opportunities){
       //add your checks
    }
  }
}

 

All Answers

Danish HodaDanish Hoda
Hi Kiran,
You can have the code like this:
List<Account> acctsWithOpps = [SELECT Id,Name,(SELECT Id,Name FROM Opportunities) FROM Account WHERE Id IN :Trigger.New]);
for(Account acc : acctsWithOpps){
  if(!acc.Opportunities.isEmpty()){
     for(Opporutnity opty : acc.Opportunities){
       //add your checks
    }
  }
}

 
This was selected as the best answer
KiranNaiduKiranNaidu
Thank you Danish for the code, this helped me in understanding.