function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
dnvansantdnvansant 

How to efficiently string relationships together? (A sub-sub query)

On an opportunity trigger, I want to update the oldest campaignmember that is related to a contactrole that is related to the trigger opportunity. I assume I can get the oldest campaignmember with a sort and limit, but I'm having trouble getting the ID for that campaignmember because I can't figure out how to link three relationships together (CampaignMember ==> ContactRole ==> Opportunity).

 

Anyone know how to do this efficiently?

 

Thank you.

 

-Derek



Best Answer chosen by Admin (Salesforce Developers) 
dnvansantdnvansant

Answered my own question. Code Below. In case anyone's interested, this marks the oldest campaignmember record associated with an opportunity contactrole by checking the campaignmember checkbox "Opportunity Credit". This gives the ability to give first touch credit for a campaign-opportunity combination.

 

 

 

 

 

trigger PrimaryCampaign on Opportunity (after update) {
public set<Id> oppid = new Set<Id>();
public list<CampaignMember> CampaignMemberToUpdate = new List<CampaignMember>();
opportunitycontactrole Cr;
Campaignmember cam;


for (Opportunity o: Trigger.New)

{
oppid.add(o.id);   
List<CampaignMember> cm = [select ID from campaignmember where contactid in (select contactid from opportunitycontactrole where opportunityid = :oppid) order by Response_Date__c asc limit 1];

if(cm.size()>0){
for(CampaignMember cmc: [Select Id, Original_Campaign__c From CampaignMember where Id in :cm])
CampaignMemberToUpdate.add(new CampaignMember(Id=cmc.Id, Opportunity_Credit__c=true));
if(CampaignMemberToUpdate.size()>0){update CampaignMemberToUpdate;}

}}}