Friday, June 24, 2016

How To Write a SOQL To Fetch All Events Related to Account and Opportunity

Scenario:

Usually when we are writing any kind of SOQL queries on related objects we always known that this particular child record always be linked to specified parent object record. For example if you have a relationship between Account(Parent) and Contact(child) that means every contact record is related any one the account record not to any ABC__c or BCD__c objects.

But where in case of Task or Events if you could see we can't guarantee that these Tasks or Events are always related to a Account records or Contact Records because these Task or Events can be linked to any one of the Contract,Campaign,Account,Opportunity,Product,Asset,Case,Solution,Quote and Any Custom Objects .

Question:
In such type of situations the Task or Event that is linked to which object it's not a static and it's gets varies based on the Event that your creating for which object(Called as Polymorphic Relationship).Now If you want to fetch all Events related to Account and Opportunity only.How we need to write a SOQL query ?



Solution:

We already know that WhatId filed in Event or Task for deciding for which object this is linked /created.So with the help of TYPE qualifier on WhatId we can achieve this.The TYPE qualifier on field always determine the object type that is referenced for Task or Event.Use this TYPE clause on where condition of SOQL to control the result.

SELECT Id,subject,What.Type,whatId 
FROM Event
WHERE What.Type IN ('Account', 'Opportunity')

This above SOQL query returns all the Events related to Account and Opportunity only.


You can also apply comparison operators such as '=' or LIKE on WHERE condition of TYPE clause .


[SELECT Id,subject,What.Type,whatId 
FROM Event
WHERE What.Type like '%Accou%']

[SELECT Id,subject,What.Type,whatId 
FROM Event
WHERE What.Type ='Position__c']

They are multiple other ways also to do same.So we will discuss all those things in my next post.

Thanks for visiting...Enjoy!!!


No comments:

Post a Comment