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
Sumant KuchipudiSumant Kuchipudi 

How to get a field from Parent's another child record?

Hi,

I have custom object which has a Account ( lookup ) and that account has Contact record. How can I get Contact's external Id (custom field) value ?  Please advice.

Thanks
Best Answer chosen by Sumant Kuchipudi
Raja Kumar PallepatiRaja Kumar Pallepati
Hi Sumant,

As you have multiple contacts associated to account, you need to gather all the account ids related to the custom object records.
You can fetch the respective contact (with fields) using SOQL parent child relationship query as below.
 
Set<Id> acctIds = new Set<Id>();
// use the logic to fetch the account ids related to your custom object records
for(Account acct : [SELECT Id, Name, (SELECT Id, Name FROM Contacts) FROM Account 
                   WHERE Id IN :acctIds]) {
                       // you can use your contact external id field in the SOQL query
    for(Contact c: acct.Contacts) {
        System.debug('Account: ' +acct.Name + 'Contact Name: '+c.name);
    }
}

Useful SOQL query reference link: https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_relationships_query_using.htm

Hope it helps you.