Search code examples
salesforceapexsoql

How to query a lookup on a lookup in salesforce SOQL


I have an record type of case which has a lookup to an Opportunity which has lookup to Account. When a query is run with workbench it works fine and I can get the account- however when its run in apex only the Opportunity ID is returned, not the account. I am new to salesforce but this is driving me crazy- the fact that the query tool and the code would return different information is beyond me- any advice would be great!

SELECT RelatedOpportunity__r.Account.Name
FROM Case
         

enter image description here

from apex:

(Case:{RelatedOpportunity__c=0061k00000B5GqiAAF, Id=5001k00000FwaivAAB})

Solution

  • Everything is queried same way, write your code "normal".

    System.debug(myCase) focuses on what's important, what's really on "this" record. It doesn't go "up" via lookups and "down" via subqueries (if you have any). It'd spam the debug logs too much.

    (well, not even that. It's not System.debug's fault. It's supposed to emit strings. A case is an object, not a string so a toString() is called on it)

    You can System.debug(myCase.RelatedOpportunity__r.Account); and you'll get your name. Or play with System.debug(JSON.serializePretty(myCase));

    Even better - try to learn the right way from the start. Checking your code's flow by spamming debugs is passe. There's no true debugging of Apex (you can't attach say interactive debugger like with .NET, can't add breakpoints and pause execution like in JavaScript) but all cool kids use https://trailhead.salesforce.com/en/content/learn/projects/find-and-fix-bugs-with-apex-replay-debugger/apex-replay-debugger-debug-your-code, check it out.