i have a custom object Case_Contacts__c which has lookup to contact object, Case_Contacts__c has field named Contact_Expiry_Date__c. i want to retrieve that field in contact list in controller.

Current Code:

List<Contact> ConList = new List<Contact>(
    SELECT FirstName, lastName, account.Name, Accountid
    FROM Contact
    WHERE id IN :conIdList

List<Case_Contacts__c> cslist = new List<Case_Contacts__c>();
for(contact c:ConList)
    Case_Contacts__c c1 = new Case_Contacts__c();
    c1.Contact__c = c.id;

1 Answer 1


Understanding Relationship Names, Custom Objects, and Custom Fields provides necessary information about how to do it in one soql:

List<Contact> conList = [
    select Id, FirstName, LastName, AccountId, Account.Name, (
        select Id, Contact_Expiry_Date__c
        from  Case_Contacts__r
    from Contact
    where id in :conIdList

for(Contact cont :conList){
    List<Case_Contacts__c> caseContacts = cont.Case_Contacts__r;
    for(Case_Contacts__c caseContact :caseContacts){
        // do something with caseContact.Contact_Expiry_Date__c field

I can be wrong with child relationship name Case_Contacts__r. In first link of this answer you will find how to find correct one.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .