Problem:-
In Event object, WhatId field can refer to 'Account', 'Opportunity', 'Campaign', custom objects etc. I want to write a SOQL query which will return different set of fields based upon which object 'WhatId' is referring to.
Solution:-
Before Winter'13 release, you have to do extra work when making queries that involve polymorphic relationships. Since you don’t know in advance what type of object is being referenced, you might have to get the ID of a Name object instead, process this information in some logic code, and then do a second query using information from that Name object to get to the content of the referenced object.
With Winter'13, salesforce has introduced the concept of Polymorphic SOQL.
Polymorphic Relationship:-
A polymorphic relationship is a relationship where the referenced objects can be one of several different object types. For example, the What relationship field in an Event can reference an Account, or a Campaign, or an Opportunity. The LastModifiedBy relationship field in an Event, however, can only reference a User and is not polymorphic.
With SOQL polymorphism you can provide instructions directly in the SOQL query on what to do for each possible type of object. You do this via the new TYPEOF clause. Something like below
SELECT Subject,
TYPEOF What
WHEN Account THEN Phone, NumberOfEmployees
WHEN Opportunity THEN Amount, CloseDate
END
FROM Event
You may have to contact saleforce.com to enable this feature for your organization.
i really like this article please keep it up.
ReplyDeleteInsurance
Hi,
ReplyDeleteDo you know which objects (other than Event and Task) in Salesforce have Polymorphic relationships?
Thanks.