[SalesForce] Relationship Query to Get All Events Associated with Account

I have the following query that works for getting all the Tasks and Events for a Lead.

[SELECT ID, activity_count__c, 
(SELECT ID FROM Tasks WHERE Status = 'Completed'), 
(SELECT ID FROM Events) FROM Lead WHERE ID IN :leadIds];

I tried to convert it to get all the Tasks and Events for an Account, like so:

[SELECT ID, activity_count__c, 
(SELECT ID FROM Tasks WHERE Status = 'Completed'), 
(SELECT ID FROM Events) 
FROM Account WHERE ID IN :accountIds];

However, the result was that I only received the Events and Tasks made on the account directly, and not on the objects associated with the account, such as Opportunities, Contacts, Cases, etc.

Is there a way to get all the data from the Account and its associated objects in a single SOQL query? Or, do I need to query each of the associated objects and parse each set of results separately?

Best Answer

The short answer is not easily, or at least not with a single query like you're showing above. If the WhatId is not associated directly with the account, you would need to query all related objects to the account, then the associated tasks. If this is in a trigger, making it bulk safe is going to involve a couple of maps.

Related Topic