Search code examples
salesforceapexsoql

Attachments in Apex SOQL Subquery


I have custom objects Team member and Employment, and there's a lookup relationship from employment(many) to team member(one), plus another lookup record on team member called current employment.

The employment record may have attachments.

I want a SOQL query, to run in an APEX class, which will return attachments information for specific team members.

So far I have this:

SObject[] results = [select id,(select id,name from Attachments) from Employment__c where id in (select Current_Employment__c from Team_Member__c where id=:id)];

Wnen I run the query in the schema browser, it works OK and I'm able to drill-down to the attachments, but when I run it in Apex (Anonymous), the result set does not contain the attachments:

for (SObject result : results) {
  System.debug(result);
}

I can only see the Employment id in the results.

How can I get attachments in APEX?


Solution

  • You do following to get list of attachment related to that object.

    Employment__c[] results = [select id,(select id,name from Attachments)  from Employment__c where id in (select Current_Employment__c from Team_Member__c where id=:id)];    
    
    for (Employment__c result : results) {
       if(result.Attachments!=null){
           List<Attachment> AttachmentList=result.Attachments;
       }
    }