Search code examples
salesforcesoql

How to access to column that is returned SOQL relationship query?


Following code is not working. The error message is "Compile Error: Initial term of field expression must be a concrete SObject: LIST at line 8 column 16" (return line is line 8)

public String getX(){

    List<Oppoinvoice__c> o = [SELECT  Opportunity__r.Account.Name  FROM Oppoinvoice__c];

    return o.Opportunity__r.Account.Name;    
}

Solution

  • You must specify what entry number of the list must be shown. With your query you will get back a list. And your method must return a string.

    public String getX(){
    
        List<Oppoinvoice__c> o = [SELECT  Opportunity__r.Account.Name  FROM Oppoinvoice__c];
    
        return o[0].Opportunity__r.Account.Name;    
    }
    

    Or like this:

    public String getX(){
    
        String o = [SELECT Opportunity__r.Account.Name FROM Oppoinvoice__c Where Id = 'XXXXXXX'].Opportunity__r.Account.Name;
    
        return o;    
    }