I would like to query all notes & attachments, lets say for an Account.
I uploaded 2 different files in the notes and attachment area but if I do the query:
select id from attachment
I do not get anything back.
If I make a query against Notes:
select id from Note
same result. I get one result back but this is a different Note
The query:
SELECT Id, ParentId from ContentDocument
gives me the correct values but the ParentId is empty. Therefore, I do not know which Documents are for which accounts.
Any ideas how to query it in the right way? Currently, SF has too many different kind of "documents" like files, notes, attachments etc. from my point of view.
Best Answer
Salesforce has two sorts of notes and attachments. There's the Classic type, represented by the
Note
andAttachment
sObjects, and the Lightning type, represented by the Content suite of objects -ContentDocument
,ContentVersion
,ContentDocumentLink
, andContentNote
. These two types are accessed in quite different ways.The classic
Note
andAttachment
records have a single polymorphic lookup to the record to which they're attached. You can query them simply:In the Lightning world of Content, the object model is quite a bit more complex. Both Notes and Attachments are represented as
ContentDocument
, a parent object over potentially multipleContentVersion
records. TheContentDocument
is then linked to all of the locations in which it's been shared, which may be many, viaContentDocumentLink
.To make things even more confusing, there's a facade object,
ContentNote
, that acts like aContentDocument
with a singleContentVersion
inherent in itsContent
field. You'll mostly have to worry aboutContentNote
if you're adding Notes, however.Anyway - not to try to summarize the substantial complexity involved in the Content system - to query both Notes and Attachments in the Lightning style for some object whose Id is
myRecord
, you'd doThis will return both
ContentNote
and regularContentDocument
Attachments. If you want just Notes, query onContentNote
rather thanContentDocument.
If you want just Attachments and not Notes, filter onFileType != 'SNOTE'
.To get the actual content, for
ContentDocument
, you can execute aContentVersion
query againstContentDocumentId
andIsLatest = true
. ForContentNote
, you can simply ask for theContent
field in yourContentNote
query, which is a Blob field.To delete records, you only need to
delete
the top-levelContentDocument
record. That will take theContentDocumentLink
records with it. DeletingContentDocumentLink
records may make an Attachment inaccessible, but it won't be deleted entirely.