Search code examples
salesforceapexsoql

How do I get info from lookup in salesforce query


I have a custom salesforce object Installation__c and it has a custom field Product__c which is a lookup to a custom object Product__c I am trying to get the fields from the child object using these query:

public with sharing class InstallationController {
    @AuraEnabled
    public static List<Installation__c> getItems() {
        // Perform isAccessible() checking first, then
        return [SELECT Id, Name, Installation_Display_Name__c, Product__c, Status__c, (SELECT Product__c.Name FROM Product__c)  FROM Installation__c];
    }
}

I get the error:

Didn't understand relationship 'Product__c' in FROM part of query call. If you are attempting to use a custom relationship, be sure to append the '__r' after the custom relationship name. Please reference your WSDL or the describe call for the appropriate names.

I have tried changing the Query to FROM Product__rand FROM Product__c__r but neither seems to work, how do I fix my query?


Solution

  • If you're traversing up or down a relationship hierarchy, the __c suffix becomes __r (r for 'relationship') until you finally get to the field that you're looking for (which still ends in __c if it's a custom field). So in your case, it will be

    public with sharing class InstallationController {
        @AuraEnabled
        public static List<Installation__c> getItems() {
            // Perform isAccessible() checking first, then
            return [SELECT Id, Name, Installation_Display_Name__c, Product__r.Name, Status__c FROM Installation__c];
        }
    }
    

    So, the change here is, for the relationship you have to use Product__r.Name