0

Why does A work but not B? For B I receive the error: "Variable does not exist: Contacts".

A

List<Account> accts = [SELECT id, (SELECT id FROM CONTACTS) FROM Account];
List<Contact> cons  = new List<Contact>();
for(Account a : accts) {
    for(Contact con : a.Contacts) {
        cons.add(con);
    }
}
system.debug(accts);
system.debug(cons);

B

List<Account> accts = [SELECT id, (SELECT id FROM CONTACTS) FROM Account];
List<Contact> cons  = accts.Contacts;
system.debug(accts);
system.debug(cons);

1 Answer 1

0

The error is telling you there's no variable called contacts on the object List. The only properties you can use are listed in the documentation.

This error occurs because you can't access an individual properties of a record from a list of records. If you had a single record:

Account acct = [SELECT id, (SELECT id FROM CONTACTS) FROM Account LIMIT 1];

Then, of course, you'd be allowed to assign those contacts.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .