+ Start a Discussion
Kenn K.Kenn K. 

I would like to retrieve a value in a relationship query

I have this query,

 

list<Contact> relatedContacts = [select id, AccountId, (Select Id From Cases) from Contact where id IN :contactIds ];

 

The thing is, I want to get the value of the cases Id  so I can use it to update another field.

 

How do I go about getting this value?

 

Thanks,

-K

 

Best Answer chosen by Admin (Salesforce Developers) 
Alok_NagarroAlok_Nagarro

Hi Ken,

 

Since there is parent-child relationship between contact & case that means 1 contact may have multiple cases.

Hence from the query you get list of cases for every contact record. So you may have many caseId for 1 contact record.

To access these ids try the code given below -

 

list<Contact> relatedContacts = [select id, AccountId, (Select Id From Cases) from Contact where id IN :contactIds ];

for(Contact con : relatedContacts)

{

 for(Case c : con.Cases)

 {

  // here you can collect case id i.e - c.id either in list or set

 }
}

All Answers

Alok_NagarroAlok_Nagarro

Hi Ken,

 

Since there is parent-child relationship between contact & case that means 1 contact may have multiple cases.

Hence from the query you get list of cases for every contact record. So you may have many caseId for 1 contact record.

To access these ids try the code given below -

 

list<Contact> relatedContacts = [select id, AccountId, (Select Id From Cases) from Contact where id IN :contactIds ];

for(Contact con : relatedContacts)

{

 for(Case c : con.Cases)

 {

  // here you can collect case id i.e - c.id either in list or set

 }
}

This was selected as the best answer
Kenn K.Kenn K.

Thanks. That was fast.. and it worked like a charm!

 

Cheers,

-K