I'm calling this query inside a before_delete handler, and the query only returns a single CampaignMember even when the Contact.Id is related to many CampaignMembers. When I run this query in anonymous execute it retrieves multiple CampaignMembers. How can I retrieve multiple related CampaignMembers while running this query in APEX?

public static void query(Map<Id, Contact> forDeletion) {
    Set<Id> contacts = forDeletion.keySet();
    for(CampaignMember campaignMember : [
            SELECT Contact.id,
            FROM CampaignMember
            WHERE Contact.id IN :contacts]) {
        losingCampaignMembers.put(campaignMember.ContactId, campaignMember);

You haven't included all of the relevant code, but I'm guessing you have this declaration somewhere in your code:

static Map<Id, CampaignMember> losingCampaignMembers;

The thing is, you need the map value to be a List<CampaignMember>, because the relationship is many-to-one. So change the declaration to:

static Map<Id, List<CampaignMember>> losingCampaignMembers;

Additionally, you will need to change your algorithm. This type of grouping is common and often looks like:

for (CampaignMember child : [/*query*/])
    if (!groupedByParent.containsKey(child.ContactId))
        groupedByParent.put(child.ContactId, new List<CampaignMember>());
  • I get the same results even if I drop the query right in a System.debug().
    – shmuli
    Jun 25 '18 at 21:41
  • Change Contact.Id to ContactId. Never use the cross-object reference where you can just use the actual field value.
    – Adrian Larson
    Jun 25 '18 at 21:52
  • I changed it to ContactId and it retrieves the same results.
    – shmuli
    Jun 25 '18 at 22:10
  • 1
    @AdrianLarson - A bit of an off topic performance thing but I remember this post: salesforce.stackexchange.com/questions/179661/… - all the time when I am checking maps for values in a loop like this. No longer use containsKey in these situations now.
    – Eric
    Jun 25 '18 at 22:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.