2

Can anyone tell me how to access the child records in parent child relationship?
My code snippet follows:

List<Account> acc = [SELECT Id,Name,(SELECT Id,LastName FROM Contacts) FROM Account];   
for(Account  a: acc){    
     System.debug('CAaount name:'+ a.Name);   

//I don't know how to access contact s here       
for(Contact c:a.Contacts)     
{ System.debug('Conatct Last:' +c.LastName);   
}
1

You can try this..

List acc = [SELECT Id,Name,(SELECT Id,LastName FROM Contacts) FROM Account];
for(Account a: acc){
    system.debug('Account name:'+ a.Name);

    List<Contact> Con = a.getSObjects('Contacts');
    for(Contact c:Con){ 
    system.debug('Contact Last:' +c.LastName);
    }
}
0
0

Too simplify very much..

for (Account a: acc)
{
    for (Contacts con : acc.Contacts)
    {
        //Anything
    }
}
0

and even simpler

for(Account  a: [select id, name, (select id, lastname from Contacts) from Account])
  for (Contact c: a:contacts) {
    system.debug(c.lastname + ' is a contact on ' + a.name);
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.