0

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;
    cslist.add(c1);
} 
0
3

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.

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.