I've created a custom object(File__c) which can be related to any standard or custom object. Currently I'm doing it with 2 fields, one to store the destination object id(String), and one for destination object type(String). If destination object type wasn't a variable, this would ideally be a lookup relationship.
Is there a way to create lookup using just the destination object id & without knowing the destination object type? Any other better way to do this?
Best Answer
Every object type results in a unique (on the org) three character prefix applied to the IDs for the records of that object type.
Since you are storing the ID as a string, if you need to select
File__c
records that "relate" to records of a given object you can use DescribeObjectResult.getKeyPrefix to translate an object type to an ID prefix, thus:You can then use this in your query, like:
(I have assumed the field holding the ID as a string is called
RecordId__c
.)On the other hand, if you are simply getting
File__c
instances and want theRecordId__c
translated to an object type, simply:From
SObjectType
you can get theDescribeObjectResult
as you need.