2
 List<Account> accs=[select id,name,Phone,
                           (select id,lastname,firstname,email 
                            from contacts) 
                     from account];

for(Account aa:accs){ 
            System.debug(aa.id);
            System.debug(aa.name);
            System.debug(aa.phone);
 }
 for(Contact con:accs.contacts){

 }

In first for loop it does not any error while second loop is giving error. I got parent values in first for loop.But i want child values too. Can any one help me please.

Thanks and regards

Kumar

1

The problem is here:

for(Contact con:accs.contacts){

accs is a list of account records, so accs.contacts isn't valid. You need to nest the contacts loop inside of the other one so that you're working with the account records themselves, not the list.

   for(Account aa:accs){ 
       System.debug(aa.id);
       System.debug(aa.name);
       System.debug(aa.phone);

       for(Contact con:aa.contacts){
           System.debug(con.firstname);
       }
   }

While I'm at it, you might want to consider some more descriptive variable names, things like aa and accs don't make for easy reading later down the line.

0

You need to do this

for(Account aa:accs){ 
            System.debug(aa.id);
            System.debug(aa.name);
            System.debug(aa.phone);

    for(Contact con:aa.contacts){

    }
 }

we use nested for loop to get inner query records.

or if you want to get only first parent record then

for(Account aa:accs){ 
            System.debug(aa.id);
            System.debug(aa.name);
            System.debug(aa.phone);
 }
 if(accs != null && accs.size() > 0)
 for(Contact con:accs[0].contacts){

 }

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.