Lookup without record type

custom-objectlookup

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:

String objectType = ...;
SObject obj = (SObject) Type.forName(objectType).newInstance();
DescribeSObjectResult describe = obj.getSObjectType().getDescribe();
String idPrefixLike = '%' + describe.getKeyPrefix();

You can then use this in your query, like:

List<File__c> files = [SELECT Id, ... FROM File__c WHERE RecordId__c LIKE :idPrefixLike ...];

(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 the RecordId__c translated to an object type, simply:

List<File__c> files = ...;

for (File__c file : files) {
    SObjectType objectType = Id.valueOf(file.RecordId__c).getSObjectType();

    ...
}

From SObjectType you can get the DescribeObjectResult as you need.