Wondering if there is anyway to query for LinkedEntityId from ContentVersion?

As i understand, ContentVersion looks up to ContentDocument which then looks up to ContentDocumentLink (could be wrong though).

When Querying for ContentVersion i attempt to look up LinkedEntityId (on ContentDocumentLink) using the following syntax


However this produces a didnt understand the relationship error. What am i missing?

Edit: The goal is the be able to relate the ContentVersions with the Entity they are linked to. After realizing ContentDocumentLink looks up to ContentDocument, this is what i've come up with

Select Id, (select Id, File_Type__c from ContentVersions), (select 
linkedEntityId from ContentDocumentLinks WHERE linkedEntityId 
='001i0000018GQ6hAAG' AND linkedEntityId != null) FROM ContentDocument

The issue is that I am retrieving all the ContentDocuments that are not filled in (hence the != null, but thats not working). Though the linkedEntityId i used is being selected (ie. their are no other ContentDocumentIds, just nulls and ones with the linkedentityid in my example


2 Answers 2

SELECT LinkedEntityId 
 FROM ContentDocumentLink 
 WHERE ContentDocumentId = :myContentVersion.ContentDocumentId

There are certain query restrictions on ContentDocumentLink


What you are trying to do in one query would be something like this:

SELECT Id, File_Type__c 
 FROM ContentVersion 
 WHERE ContentDocumentId IN (SELECT ContentDocumentId
                              FROM ContentDocumentLink
                              WHERE LinkedEntityId = :myAccountId)

However, if you try this, you get an error:

Entity 'ContentDocumentLink' is not supported for semi join inner selects

So, you'll need to use two queries in either Apex of Flow to get what you want:

Query 1:

ContentDocumentLink[] cdls = [SELECT ContentDocumentId, LinkedEntityId 
  FROM ContentDocumentLink 
  WHERE LinkedEntityId = :myAccountId];

Pivot CDLs by ContentDocumentId

...create a Map of ID => ContentDocumentLink and pivot cdls by ContentDocumentId
or just create a Set<Id> of ContentDocumentId from cdls

Query 2

ContentVersion[] cvs = [SELECT Id, File_Type__c 
   FROM ContentVersion
   WHERE ContentDocumentId IN :cdlsByContentDocumentId.keySet()];

This remark is too late for Bobbygllh but just on time for internet posternity :

You can use the field LatestPublishedVersion from ContentDocument that gives you directly the latest version of ContentVersion

So that would be :

SELECT  ContentDocument.LatestPublishedVersionId
FROM ContentDocumentLink 
WHERE LinkedEntityId = :myAccountId

You must log in to answer this question.

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