Polymorphic Relationships fields and their use in SOQL

A polymorphic relationship is a relationship where the referenced objects can be one of several different object types.

In Simpler words:

Polymorphic key is a relationship field which can relate to more than one type of object as parent. Unlike Lookup and Master-detail relationships which are related to a single object, Polymorphic keys can refer to multiple objects.


Where to find:
As of date, Polymorphic keys cannot be created by developers. They are available for specific objects out of the box for e.g. WHOID and WHATID in Task and Event objects.
Sneak Peak: Salesforce Polymorphic Keys
SOQL Polymorphism:                                                                                                                   

Before this feature we don’t have any way to get the content of the referenced object. For this first we collect the ID of a Name object and do a second query using information from that Name object to get to the content of the referenced object.
But with SOQL polymorphism we can do all of this work in a single query. 

Use TYPEOF clause to achieve the SOQL poymorphism in salesforce. 

Ex:

With SOQL polymorphism you can provide instructions directly in the SOQL query on what to do for each possible type of object. 

SELECT Subject,  TYPEOF What    WHEN Account THEN Phone,    WHEN Opportunity THEN Amount,   ENDFROM Event

This would conditionally return value of field "Phone" if event is related to Account and value of field "Amount" if event is related to Opportunity

Filter results by Type:

List = [SELECT Description FROM Event WHERE What.Type IN ('Account', 'Opportunity')];

This would return only those events which are related with an Account or Opportunity.

Similarly we also have the Who relationship field in an Event which can reference an Contact, or a Lead etc.

For more reference:Working with Polymorphic Relationships in SOQL Queries




Comments

Popular posts from this blog

List of Key Prefixes in Salesforce

SFDX Install CPQ in Scratch org