Didn't understand relationship 'LinkedEntityId' in field path

Viewed 1489

So I am generally able to query the relationships but I do not have the access to this object in object manager, so what should be the query to access accountId from ContentDocumentLink object when I know LinkedEntity is a case.

My Code:

List<ContentDocumentLink> case_file_links=
  [
  SELECT Id,ContentDocumentId,LinkedEntityId.AccountId,ShareType
  FROM ContentDocumentLink
    WHERE Id IN: case_file_link_Ids
  ];

Error:

  SELECT Id,ContentDocumentId,LinkedEntityId.AccountId,ShareType
                              ^
ERROR at Row:2:Column:45
Didn't understand relationship 'LinkedEntityId' in field path. If you..
1 Answers

LinkedEntityId is a weird mutant lookup to many tables, any table that supports File upload. Official name is "polymorphic lookup".

Maybe you worked with Tasks before, they have similar fields. WhatId can point to Account, Case, Opportunity plus many custom objects. and WhoId points to User/Contact/Lead.

So it's a lookup to "something". It's not guaranteed it's to Cases so at compile time SF can't just blindly accept AccountId. What if the field is not there.

You might have to use TYPEOF in SOQL.

SELECT Id, ContentDocumentId, ShareType,
    TYPEOF LinkedEntity WHEN Case THEN CaseNumber, Subject, AccountId END
FROM ContentDocumentLink
WHERE Id IN ('06A7a000001VafmEAC', '06A7a000001VafnEAC')

Developer Console is too stupid to display it properly but workbench should manage

enter image description here

In Apex you'll need an instanceof to check and cast the LinkedEntity to right sObject... or use the generic sObj.get('AccountId') and if it's not there it'll return null?

If this sounds like too much hassle - you can always split it into 2 queries.

  1. Query just SELECT Id, ContentDocumentId, LinkedEntityId, ShareType FROM ContentDocumentLink
  2. Loop through results, collect LinkedEntityId into a helper Set<Id>.
  3. Map<Id, Case> cases = new Map<Id, Case>([SELECT Id, AccountId FROM Case WHERE Id IN :mySet]);
Related