I need to clone all Account records along with their contact records. I'm using clone() method in Apex for this. Below is the code I have written:
List<Account> accListToClone = new List<Account>();
List<Contact> conListToClone = new List<Contact>();
Set<Id> accIdSet = new set<Id>();
Map<Id, List<Contact>> mapOfAccIdVsContact = new Map<Id, List<Contact>>();
List<Account> accs = [Select Id,Name,Phone from Account];
for(Account acc : accs){
accIdSet.add(acc.Id);
}
List<Contact> cons = [Select Id,FirstName,LastName,Phone,Account.Id from Contact where Account.Id in :accIdSet];
for(Contact con : cons){
if(mapOfAccIdVsContact.containskey(con.Account.Id)){
mapOfAccIdVsContact.get(con?.Account?.Id).add(con);
}else{
mapOfAccIdVsContact.put(con?.Account?.Id,new List<Contact>{con} );
}
}
for(Account acc : accs){
Account accClone = acc.clone(false,true,false,false);
accClone.Name = acc.Name + ' Clone';
accListToClone.add(accClone);
List<Contact> conList = mapOfAccIdVsContact.get(acc.Id);
for(Contact con : conList){
Contact conClone = con.clone(false,true,false,false);
conClone.FirstName = con.FirstName + ' Clone';
conClone.AccountId = accClone.Id; //How to get the Account clone record ID here?
conListToClone.add(conClone);
}
}
insert accListToClone;
insert conListToClone;
I'm not able to figure out how to link the cloned contact's account Id with the cloned account Id. I would need to insert the cloned account record inside the for loop which is a very bad practice. What is the work around for this?