salesforceapexapex-codesoql

System.sobjectexception: sobject row was retrieved via soql without querying the requested field: Asset.Product2


I have a problem on the query on my test class. I have put AssetId__r.Product2Id on the 1st query, and put Product2Id in the Asset query. but still the error persist. as the error says it needs Asset.Product2 which is an SObject , not a field and I am lost on how to fix this error. does anyone encounter this error before? please I need your help.


Solution

  • would be easier if you'd post the actual query.

    You probably have something like that in your code:

    String name = myObject.AssetId__r.Product2.Name;
    

    but the query SELECT AssetId__r.Product2Id, ... FROM MyTable WHERE ...

    So what you can change is put more product fields in the query. You can go up to 5 dots "up".

    SELECT AssetId__r.Product2.Id,
        AssetId__r.Product2.Name,
        AssetId__r.Product2.ProductCode
    FROM myObject 
    WHERE ...
    

    It will work and then Apex that uses it can treat AssetId__r.Product2 as a normal Product2 object, as if it was queried separately. It'll have Id, Name, ProductCode fields set.

    The query is also "safe". If AssetId__c is null or Product2Id is null - it'll still execute OK. You'll have to do null checks in Apex (or in query's WHERE clause)