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
Christopher Bahr 4Christopher Bahr 4 

Is there a way to write an SOQL query that grabs all the files attached to opportunities?

Basically I am trying to create a report on our attachments with the SOQL 2 Report (https://appexchange.salesforce.com/listingDetail?listingId=a0N3A00000FMnZuUAL) app from the appexchange. Is it possible to write a single query that would grab the attachment information from the contentversion table, link to the file, and opportunity information? 
I've tried to write one but I am getting tripped up with the polymorphic relationship and fields between the opportunity table and contentdocumentlink table.
Best Answer chosen by Christopher Bahr 4
Christopher Bahr 4Christopher Bahr 4
I ended up figuring it out. Notes are treated as files linked to the Opportunity, so I filter that filetype out.
SELECT ContentDocumentID, ContentDocument.Title, ContentDocument.FileType,ContentDocument.CreatedById,LinkedEntityId, ContentDocument.LatestPublishedVersion.CreatedDate FROM ContentDocumentLink WHERE LinkedEntityId IN ( SELECT Id FROM Opportunity ) and LinkedEntity.Type='Opportunity' AND ContentDocument.FileType != 'SNOTE' AND ContentDocument.LatestPublishedVersion.isLatest = True

 

All Answers

PriyaPriya (Salesforce Developers) 
Hi Christopher,

Kindly try this :-
SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId = '<Opportunity or other object id here>'

Kindly refer the similar ask :-

https://salesforce.stackexchange.com/questions/124640/how-to-query-all-files-attached-to-the-opportunity
 

Kindly mark it as the best answer if it works for you.

 

Thanks & Regards,

Priya Ranjan


​​​​​​​
Christopher Bahr 4Christopher Bahr 4
Thanks, but how would I join that with the Opportunity and ContentVersion tables to get the Opportunity Title/Name, File Title and other fields?

Best regards,
Chris
Christopher Bahr 4Christopher Bahr 4
I ended up figuring it out. Notes are treated as files linked to the Opportunity, so I filter that filetype out.
SELECT ContentDocumentID, ContentDocument.Title, ContentDocument.FileType,ContentDocument.CreatedById,LinkedEntityId, ContentDocument.LatestPublishedVersion.CreatedDate FROM ContentDocumentLink WHERE LinkedEntityId IN ( SELECT Id FROM Opportunity ) and LinkedEntity.Type='Opportunity' AND ContentDocument.FileType != 'SNOTE' AND ContentDocument.LatestPublishedVersion.isLatest = True

 
This was selected as the best answer