I am running a query on contentversion to fetch files related to opportunity from Salesforce. However the content version records returned from the query does not tell me what opportunity id is that related to. I know that ContentDocumentLink has a column called LinkedEntityId which would be opportunity id in my case.


Is there a way I can create a formula field on Contentversion object and lookup the LinkedEntityId from the contentDocumentLink? or Is there any other way to achieve this usecase?


  • Use a custom lookup field on ContentVersion to point at Opportunity
    – cropredy
    Oct 4, 2019 at 18:02

1 Answer 1


ContentDocumentLink is a junction object establishing a many-to-many relationship between ContentDocument (not ContentVersion) and arbitrary sObjects. The only approach you'd have to place linked sObject Ids on ContentVersion objects would be an Apex trigger. It is not possible to do this via a formula field.

However, since the relationship is many-to-many, your code must not assume that each version or document is related to exactly one record of any specific sObject unless you have other code in your Salesforce org enforcing that constraint.

  • Thanks for the help. I would most probably be fetching the latest version of the document. Also, please guide me how can I achieve it using trigger. Would that be a trigger on Contentversion object, inside the trigger I would have to query ContentdocumentLink matching on contentdocumentID. Once I get the contentdocumentLink, I just copy the value of LinkedEntity id to the custom field I created on contentversion?
    – Anonymous
    Oct 4, 2019 at 14:36
  • I wrote the trigger specified above, it throws me the error when I am copying the value of LinkedEntityId from ContentDocumentLink to the custom string field I created on Contentversion caled "LinkedEntityId" saying "the custom field LinkedEntityId is readable only". I did select "Active" in Field Usage and set "Data sensitivity level" to public. Can't figure out what are the other settings on custom field.
    – Anonymous
    Oct 4, 2019 at 15:53
  • @Anonymous I don't think that's an issue that can be diagnosed in a comment thread.
    – David Reed
    Oct 4, 2019 at 15:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .