Sub topic 10
Polymorphic relationships and TYPEOF
This chapter assumes you can write child-to-parent queries with dot notation, know that a lookup field has a relationship name, and can read basic Apex. It covers lookup fields that can point to more than one object type, and how to query them.
What makes a relationship polymorphic
A polymorphic relationship is a lookup field whose target can be one of several object types. A normal lookup, such as Contact.AccountId, always points to an Account. A polymorphic lookup does not have a fixed target.
Common examples:
Owneron many objects can be a User or a Queue.Whaton Event and Task can be an Account, Opportunity, Case, or another object.Whoon Event and Task can be a Contact or a Lead.
The relationship name (What, Who, Owner) works with dot notation, but only for fields that every possible target type shares.
Using shared fields with dot notation
Every record has a Name field on the common targets, and every target has an Id, so you can read some fields without any special syntax. The Owner path from earlier chapters is the typical case:
SELECT Id, Subject, Owner.Name
FROM TaskOwner.Name works whether the owner is a User or a Queue, because both have a Name. This approach stops working once you need a field that exists on only one target type. What.Amount is invalid, because only Opportunity has Amount.
Selecting type-specific fields with TYPEOF
TYPEOF lets you pick different fields depending on the type of the record the relationship points to. You write one WHEN branch per type you care about.
SELECT Id, Subject,
TYPEOF What
WHEN Account THEN Name, Phone
WHEN Opportunity THEN Name, Amount
END
FROM EventEach returned Event contains only the fields from the branch that matches its What record. An Event related to an Account returns Name and Phone. An Event related to an Opportunity returns Name and Amount.
You can add an ELSE branch for every other type. In that branch you may list only fields that all remaining types share, such as Id and Name.
How the query resolves each row
Filtering on the type of a polymorphic field
Because TYPEOF cannot appear in a WHERE clause, filter on the type another way. You can test the Type pseudo-field on the relationship:
SELECT Id, Subject, What.Name
FROM Event
WHERE What.Type IN ('Account', 'Opportunity')What.Type returns the object name of the related record. This filter limits which rows come back. It does not give you type-specific fields, so combine it with TYPEOF when you need both.
Reading TYPEOF results in Apex
In Apex, the polymorphic field comes back as a generic SObject. Check its real type before you cast it:
for (Event e : [
SELECT Id, Subject,
TYPEOF What
WHEN Account THEN Name, Phone
WHEN Opportunity THEN Name, Amount
END
FROM Event
LIMIT 20
]) {
if (e.What instanceof Account) {
Account a = (Account) e.What;
System.debug('Account ' + a.Name + ' ' + a.Phone);
} else if (e.What instanceof Opportunity) {
Opportunity o = (Opportunity) e.What;
System.debug('Opportunity ' + o.Name + ' ' + o.Amount);
}
}If you skip the instanceof check and cast blindly, a record of another type throws a System.TypeException. Reading a field you did not list in the matching branch throws a System.SObjectException, because that field was never queried.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Selecting `What.Amount` directly | Query error, since not every target has `Amount` | Use `TYPEOF What WHEN Opportunity THEN Amount END` |
| Using `TYPEOF` in `WHERE` | Query error | Filter with `What.Type` |
| Casting `e.What` without `instanceof` | `TypeException` at run time | Check the type first |
| Listing a type-specific field in `ELSE` | Query error | Keep `ELSE` to shared fields |
Exercise
A Task query uses TYPEOF Who WHEN Contact THEN Name, Email WHEN Lead THEN Name, Company END. In Apex, you read t.Who for a Task related to a Lead and cast it to Contact. What happens, and how do you avoid it?
Show answer
The cast throws a System.TypeException, because the record is a Lead. Avoid it by checking t.Who instanceof Lead (or instanceof Contact) before casting, and cast to the type that matches.
Exercise
You need only Events whose What record is an Opportunity, and you want the Opportunity Amount. Which two features do you combine?
Show answer
Filter with WHERE What.Type = 'Opportunity' and select the amount with TYPEOF What WHEN Opportunity THEN Name, Amount END.