Bulk Insert Accounts, add 5 Contacts to Each Account and 2 Opportunity for each Contact

Code Snippet to Insert Bulk Accounts, add 5 Contacts to Each Account, and 2 Opportunity for each Contact

Execute the below script in developer console. It will create 5 Accounts records and each Account have 5 Contacts and each Contact will have 2 Opportunities.

Set<Id> conIds = new Set<Id>();
For(integer i=0; i<1; i++) { 
	Account acc = new Account(Name='Bulk Account '+i, AccountNumber='919102'+i, Rating='Hot');
	Insert acc;
    For(integer j=0; j<3; j++) { 
        Contact con = new Contact(LastName=acc.Name +' Contact '+j, AccountId=acc.Id);
		Insert con;
        conIds.add(con.Id);
    }
}

List<Contact> lstContact = [Select Id, Name From Contact where Id in: conIds];

for(Contact con: lstContact) { 
    for(integer i=0; i<2; i++) { 
        Opportunity  oppr = new Opportunity(Name=con.Name + ' Oppor '+ i, CloseDate=System.Today() + 12,StageName='Qualification', ContactId=con.id);
        Insert oppr;
    }
}

Leave a Reply