This is the question that is usually asked in companies during interview that how can you insert records of two different objects using one single dml statement. so after reading this article you will be able to explain your interviewer that how to do this.
- First you need to create the instance of each object whether you are working with salesforce standard objects or custom objects. for example
Contact con1 = new Contact(LastName = 'anyLastName');
2. Then you need to create the list of sObject to insert those instances created above into it.
List<sObject> sObjectList = new List<sObject>();
3. Now you have to add those instances of different objects to the sObject List
sObjectList.add(acc1);
sObjectList.add(con1);
4. Now simply write one insert dml statement for sObjectList to insert both objects records simultaneously to the database.
insert sobjectList;
hope you get useful information by reading the article.
Thanks.