+ Start a Discussion
Varun AnnadataVarun Annadata 

how to get case casenumber from Attachment using a soql query?

How to get case record fields from attachments using a soql query?

like select name from attachements where parentid='some id' .how can i write a inline query in the same query to get case record field for a particular attachment?
samyuktha reddy etikayalasamyuktha reddy etikayala
Hi Varun,

Please find below code:

SObject[] queryParentObject = Database.query('SELECT Id, CaseNumber,Status, (SELECT Id, Name FROM Attachments) FROM Case');
 
for (SObject parentRecord : queryParentObject){
  Object ParentFieldValue1 = parentRecord.get('Id');
  Object ParentFieldValue2 = parentRecord.get('CaseNumber');
  Object ParentFieldValue3 = parentRecord.get('Status');
  // Prevent a null relationship from being accessed
 
  SObject[] childRecordsFromParent = parentRecord.getSObjects('Attachments');
  if (childRecordsFromParent != null) {
    for (SObject childRecord : childRecordsFromParent){
      Object ChildFieldValue1 = childRecord.get('Id');
      Object ChildFieldValue2 = childRecord.get('Name');
      System.debug('Case Id: ' + ParentFieldValue1 + ' Case Number: ' + ParentFieldValue2 + ' Case Status: ' +     ParentFieldValue3 + ' Att Id: '+ ChildFieldValue1 + ' Att FileName: ' + ChildFieldValue2);
    }
  } 
}

Hope it may helpful for you.

Thanks and regards,
Samyuktha.
 
Nayana KNayana K
Not sure whether this helps or not.

Check below links:
https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_typeof.htm
https://salesforce.stackexchange.com/questions/34528/how-to-access-field-from-related-record-via-what-or-who-field

I tried below query in workbench which retrives Case's attachment only:
SELECT TYPEOF Parent WHEN Case THEN CaseNumber END FROM Attachment WHERE ParentId IN (SELECT Id FROM Case)


SELECT TYPEOF Parent WHEN Case THEN CaseNumber END FROM Attachment WHERE ParentId =: someCaseId