We already knew that Account and Contact have relationship where as Account is parent. I created one more child for Account called RelateObj. But there is no any relation between RelateObj and Contact.

Now, I want to get Account and Contact records with respect to RelateObj. I tried with this by using Apex collection and it gives this error:

SObject row was retrieved via SOQL without querying the requested field: Contact.Account` and the class is listed below.

public class Example {

    public static List<childtoacc__c> findSiblings() {

    List<Contact> children = [select id,LastName from contact];
    List<RelateObj__c> values = new List<RelateObj__c>();
    Set<Id> parentIds = new Set<Id>();
       for (Contact child : children) {
             values = [SELECT Id,name FROM RelateObj__c WHERE Id IN :parentIds];
       return values;

Why do I get this error? Can we achieve this functionality only using SOQL?

1 Answer 1


As the error said, you didn't select the Account.Id field from the list of contacts. But I see an another problem. Your values variable is set in the for loop. Here's the right code:

public class Example {

    public static Map<RelateObj__c, List<Contact>> findSiblings() {

    List<Contact> children = [select id,LastName, Account.Id from contact];
    Map<Id, List<Contact>> contactsByAccountId = new Map<Id, List<Contact>>();
       for (Contact child : children) {
                  List<Contact> contacts = new List<Contact>(){child};
                  contactsByAccountId.put(child.Account.Id, contacts);

       Map<RelateObj__c, List<Contact>> contactsByRelatedObjs = new Map<RelatedObj__c, List<Contact>>();
       for(RelateObj__c relateObj : [SELECT Id,name, Account__c FROM RelateObj__c WHERE Account__c IN :contactsByAccountId.keySet()){
             contactsByRelatedObjs.put(relateObj, contactsByAccountId.get(relateObj.Account__c));

       return contactsByRelatedObjs;
  • sometimes we did not observe small mistakes. I rectified the error. But the values variable showing null in resulting even i objects have records. Do you have any idea about this?
    – user40339
    Commented Jan 9, 2017 at 13:24
  • Is RelateObj__c a custom object? How the contact object and the RelateObj__c object are related? Commented Jan 9, 2017 at 13:29
  • Yes, RelateObj__c is a custome object. But there is no any relation between Contact and RelateObj__c objects.
    – user40339
    Commented Jan 9, 2017 at 13:32
  • How are the Account object and the RelateObj__c are related? Commented Jan 9, 2017 at 13:32
  • Account and RelateObj__c objects are related with Lookup
    – user40339
    Commented Jan 9, 2017 at 13:34

You must log in to answer this question.