Contents
How to use polymorphic relationships in soql queries?
For example, the Who relationship field of a Task can be a Contact or a Lead. The following describes how to use SOQL queries with polymorphic relationships in Apex.
How to enable polymorphic soql in Salesforce?
Ask Salesforce Support to enable “Polymorphic SOQL” in your organization, then you’ll be able to determine whether it’s Lead or Contact. It’s in Developer Preview at the moment but it’s pretty neat.
How to get task object record using soql?
Instead, you’ll have to do 2 SOQL queries, the first to get the Task information and the second to get the info from the Contact or Lead that the Who is pointing to. Ask Salesforce Support to enable “Polymorphic SOQL” in your organization, then you’ll be able to determine whether it’s Lead or Contact.
Can you query the whoid and whatid fields of Task?
Because the WhoId and WhatId fields of Task are polymorphic (i.e. can point to many different kinds of objects) you can’t just query relationships through them like you can for normally-related objects.
When to use typeof in a polymorphic query?
TYPEOF is only allowed in the SELECT clause of a query. You can filter on the object type of a polymorphic relationship using the Type qualifier in a WHERE clause, see Filtering on Polymorphic Relationship Fields for more details.
How to query parent fields from polymorphic lookup?
You can do that by specifying the What.Type in the where clause like below. SELECT Id FROM Event WHERE What. Type IN ( ‘Account’, ‘Opportunity’ ) Now in the above example, what if we need to query some fields from Opportunity and Account. Let’s say Phone from Account and CloseDate from Opportunity.
When to use the typeof clause in soql?
TYPEOF is an optional clause that can be used in a SELECT statement of a SOQL query when you’re querying data that contains polymorphic relationships. A TYPEOF expression specifies a set of fields to select that depend on the runtime type of the polymorphic reference.