1

I have a Case object related to a Custom Object work part (Api Name- Work_Part__c ). Case is the parent object. I am trying to fetch all the work parts related to a case using below query

List<Case> c = new List<Case> ();
c =[Select Id from Case where Id ='5006F00001tjI5S'];
system.debug('size' + c.size());
system.debug('Workparts' + c[0].work_parts__r.size());

In the debug log, size is 1 , but the Workparts value is 0. Though the case with Id '5006F00001tjI5S' has 2 work parts as the related list. I triple checked relationship name is work_parts__r . Not sure, what I am missing.

2

As with any data you wish to access in Apex, you must include the child objects in your query. Specifically, you must perform a SOQL parent-child query using the relationship name Work_Parts__r:

c = [SELECT Id, (SELECT Id, ... other fields ... FROM Work_Parts__r)
     FROM Case
     WHERE Id = ...];

Only then can you access c[0].Work_Parts__r as a List. Note that the size() of c is the number of Case records, while the size() of c[0].Work_Parts__r is the number of Work_Part__c records associated with the first result Case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.