function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ 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,
Nayana KNayana K
Not sure whether this helps or not.

Check below links:

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