[SalesForce] SOQL Query on Event to get Opportunity (custom fields)

I need help to query on Task Event to get Opportunity custom fields like Campaign name and Product name.
I would like to filter my tasks related to Oppty and Lead based on product name and campaign name.

String LeadObjName= 'Lead';
        String OpportunityObjName= 'Opportunity';
        String Completedsatatus= 'Completed';

String queryStr='select Id, Subject, Status,ActivityDate,Priority, OwnerId, Owner.Name, Owner.IsActive,Description,WhoId,Who.Name,WhatId, What.Name,AccountId,Account.Name ';
            queryStr+=' from Task where OwnerId = :userId and (Who.Type =:LeadObjName OR What.Type = :OpportunityObjName ) ';
            queryStr+=' and Status !=:Completedsatatus';
            queryStr+='  order by ActivityDate ASC, Priority DESC';

Ques: We want to access opportunity and lead custom fields in my query but not able to add custom fields here in this query
Thanks in Advance!

Best Answer

You cannot do this in a single query because WhatId is polymorphic (...unless your organization has the SOQL Polymorphism feature enabled, which is in Developer Preview).

What you'd need to do is query on Task and Event to find those records that are interesting to you, filter based upon their WhatId values (for example, you can look for a WhatId that starts with 006 to find Opportunities), and accumulate the WhatId values in separate sets by object type. So you'd have, say,

Set<Id> opportunityWhatIds;
Set<Id> leadWhatIds;

and you'd populate them by looping over your Task and Event records.

You'd then have to run one additional query per sObject, using a WHERE Id IN :opportunityWhatIds clause, to obtain the information from that parent object.

Related Topic