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
GirinoobGirinoob 

Relational SOQL query between contact and campaign member

Hello,

I want to know how to write a relational soql query between contact and campaignmember. 

I need to display list of contact details having relationship with campaign member.

 

Thank you.

Best Answer chosen by Admin (Salesforce Developers) 
Yoganand GadekarYoganand Gadekar

You can try this:

 

for(contact con:[select name,id,(select id from CampaignMembers) from contact]){
     List<CampaignMember > camList = New List<CampaignMember>();
     for(CampaignMember camp: con.CampaignMembers){
     camList.add(camp);
}
System.debug('All the campaignmemeber's under contact '+con.name+'are'+camList );
}

 

 

Mark this as answer if this works:-)

Thanks and Regards,

Yoganand Gadekar.

All Answers

harsha__charsha__c

You can form query for this from the eclipse schema..!

GirinoobGirinoob

How to do ? can u explain me ? I am new to salesforce development.

 

Thank you

Jake GmerekJake Gmerek

So it looks like contacts and campaignmembers have a relationship but in the opposite direction to the one that you are asking for. In other words, one contact could have a list of campainmembers, but a campaignmember can have at most one contact.  Let me know what you are looking for after seeing this and I will see what I can do to help.

Yoganand GadekarYoganand Gadekar

You can try this:

 

for(contact con:[select name,id,(select id from CampaignMembers) from contact]){
     List<CampaignMember > camList = New List<CampaignMember>();
     for(CampaignMember camp: con.CampaignMembers){
     camList.add(camp);
}
System.debug('All the campaignmemeber's under contact '+con.name+'are'+camList );
}

 

 

Mark this as answer if this works:-)

Thanks and Regards,

Yoganand Gadekar.

This was selected as the best answer
Raj.ax1558Raj.ax1558

Hi,

 

firstly you fetch contact, make a contact list  suppose - 

list<contact> con = [SELECT id FROM contact];

 

and fetch all campaignmember records -\

 list<campaignmember> cmlist = [SELECT id, contactid FROM campaignmember];

 

create a new contact list -

list<contact> conlist = new list<contact>();

 

now-

for(campaignmember cm : cmlist)

{

     for(contact c : con)

    {

             if(c.id == cm.contactid)

                              conlist.add(c);

     }

}

 

 

Thank You

 

mark this as solution for others to get it easily

 

RajashriRajashri
Hi Yoganand

Can you please send me whole controller code..

I have same requirement...

Thanks

 
RajashriRajashri
Hi Raj,

I tried your code but i am getting an error that
Illegal assignment from LIST<CampaignMember> to LIST<CampaignMember>..

Why so?