A polymorphic relationship is a relationship between objects where a referenced object can be one of several different types. For example, the Who relationship field of a Task can be a Contact or a Lead.
You can use SOQL queries that reference polymorphic fields in Apex to get results that depend on the object type referenced by the polymorphic field.
One approach is to filter your results using the Type qualifier.
SOQL Syntax :-
SELECT Description FROM Event WHERE What.Type IN ('Account', 'Opportunity')
Type Of :-
Salesforce has provided an optional TYPEOF clause that can be used in a SOQL query including polymorphic relationships. TYPEOF clause is available in API version 46.0 or LATER. Let's solve our issue first and then we'll see the format of TYPEOF clause in detail.
SOQL Syntax :-
SELECT TYPEOF What WHEN Account THEN Phone WHEN Opportunity THEN Amount END FROM Event
SOQL some Examples :-
This example queries Events that are related to an Account or Opportunity via the What field.
//Account and Opportunity
Select Id, Subject from Task Where What.Type IN ('Opportunity', 'Account')
// we are using “TYPEOF Who”, This means based on whoId if it is related to contact then we are getting the Name
//or If the whoId is related to Lead then we are getting the Name and Phone.
SELECT Id, Status, Subject, TYPEOF who WHEN Contact THEN Name WHEN Lead THEN Name, Phone END FROM Task
//More Example
SELECT Id, Owner.Name FROM Event WHERE Owner.Type = ‘User’
//More and More Example
SELECT Id, Who.Id, Who.Type FROM Task
//More Cube Example
SELECT Id, Who.FirstName, Who.LastName FROM Task WHERE Owner.FirstName LIKE ‘SHR%’
//More Example
SELECT TYPEOF What WHEN Account THEN Phone WHEN Opportunity THEN Amount END FROM Event
instanceof Keyword :-
If you need to access the referenced object in a polymorphic relationship, you can use the instanceof keyword to determine the object type. The following example uses instanceof to determine whether an Account or Opportunity is related to an Event.
Apex Syntax :-
Event myEvent = eventFromQuery;
if (myEvent.What instanceof Account) {
// myEvent.What references an Account, so process accordingly
} else if (myEvent.What instanceof Opportunity) {
// myEvent.What references an Opportunity, so process accordingly
}
Apex Example User Case :-
List <Task> listTask = [SELECT TYPEOF What
WHEN Account THEN Phone, NumberOfEmployees
WHEN Opportunity THEN Amount, CloseDate
ELSE Name
END
FROM Task
WHERE What.Type In ('Account','Opportunity')];
for (Task tsk: listTask) {
if (tsk.What instanceof Account) {
Account acc = tsk.What;
System.debug('--acc--->'+acc.NumberOfEmployees);
} else if (tsk.What instanceof Opportunity) {
Opportunity opp = tsk.What;
System.debug('--opp--->'+opp.CloseDate);
}
}
feature :-
read more :-
