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
Monali NandaMonali Nanda 

How to add Related object records in a List/Array of same object ?

I wanted to add Related Contact records from Account Object in a Contact array. But I'm getting  error in doing so.
 
Account[] acctsWithContacts = [SELECT Name, (SELECT FirstName,LastName FROM Contacts)FROM Account limit 10];   
                              
// Get child records 
 
Contact[] cts = acctsWithContacts.Contacts;    //(Here I'm getting the error)
 
System.debug('Name of first associated contact: ' + cts[0].FirstName + ', ' + cts[0].LastName);
AnkaiahAnkaiah (Salesforce Developers) 
Hi Monali,

try with below in dev cosole.
Account[] acctsWithContacts = [SELECT id, Name FROM Account];
Contact[] conlist;

set<id> accids = new set<id>();

for(account acc:acctsWithContacts){
   accids.add(acc.id);
}
system.debug('acctsWithContacts=='+acctsWithContacts);
system.debug('acctsWithContactssize=='+acctsWithContacts.size());

 conlist= [select id,FirstName,LastName from contact where AccountId=:accids];

system.debug('conlist=='+conlist);
System.debug('Name of first associated contact: ' + conlist[0].FirstName + ', ' + conlist[0].LastName);

If this helps please mark it as best answer.

Thanks!!​​​​​​​
ravi soniravi soni
Hi Monali,
try below code and get the reference. I believe it will work.
Account[] acctsWithContacts = [SELECT Name, (SELECT FirstName,LastName FROM Contacts)FROM Account limit 10];   


list<Contact> lstContact = new list<Contact>();

for(Account Acc : acctsWithContacts){
for(Contact con : Acc.Contacts){
lstContact.add(con);
}
    
}

system.debug('lstContact=====>' + lstContact.size() ) ;

don't forget to mark it as the best answer.
Thank you