[SalesForce] Any way to Query for LinkedEntityId from ContentVersion

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

ContentDocument.ContentDocumentLink.LinkedEntityId

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

Best Answer

SELECT LinkedEntityId 
 FROM ContentDocumentLink 
 WHERE ContentDocumentId = :myContentVersion.ContentDocumentId

There are certain query restrictions on ContentDocumentLink

UPDATE

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()];
Related Topic