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
Mayank Deshpande 22Mayank Deshpande 22 

Hi All , I have requirement that when i click on save button on account object three record created

I have requirement that when i click on save button on account object three record created  in Account object  having self relationship in three records.

means ---- when user click save {A,B,C} account created and A' ID is realted with B and C record , B's ID related with A.C record and same with C 

kindly suggest how we can achive this in best possible way
Raj VakatiRaj Vakati
Option 1 :--- >

 
try {
    Account acct = new Account(Name='SFDC Account');
    insert acct;
	Contact con = new Contact(
        FirstName='Joe',
        LastName='Smith',
        Phone='415.555.1212',
        AccountId=acct.Id);
    insert con;
	
	Opportunity opp = new Opportunity(
        Name='Test',
        StageName='Closed Lost',
        CloseDate=System.today(),
		Amount=120 ,
        AccountId=acct.Id);
    insert con;
	
} catch(DmlException e) {
    System.debug('An unexpected error has occurred: ' + e.getMessage());
}



Option 2  :--- >REST API Using  Composite Resources
 
{
  "compositeRequest" : [
  {
    "method" : "POST",
    "url" : "/services/data/v38.0/sobjects/Account",
    "referenceId" : "newAccount",
    "body" : { "Name" : "New Account" }
  },{
    "method" : "POST",
    "url" : "/services/data/v38.0/sobjects/Contact",
    "referenceId" : "newContact",
    "body" : {
      "LastName" : "New Contact",
      "AccountId" : "@{newAccount.id}"
    }
  }] 
}

 
Prashant Pandey07Prashant Pandey07
Hi Mayank,
Thanks for asking a great question..
Well @Raj V  has provided the good quick solution and it will work fine for tiny class but it may hit the governor limit when you are dealing with so many dmls and triggers.  

I would recommend using insert all the record in one dml call, Using external ID fields as foreign keys. Check the sample code for your reference.

Note: This code is not compiled.
 
public class ParentChildSample {
    public static void InsertParentChild() {
      
        Account newA = new Account(
            Name='AccountInsert');
        
        // Create the parent reference.
        // Used only for foreign key reference
        // and doesn't contain any other fields.
        Account NewB = new Account(
            MyExtID__c='SAP111111');                
        newA.Account__c = NewB;
        
        // Create the Account object to insert.
        // Same as above but has a Name field.
        // Used for the insert.
        Account parentAccount = new Account(
            Name='Hallie',
            MyExtID__c='SAP111111');      
        
        // Create the account and the opportunity.
        Database.SaveResult[] results = Database.insert(new SObject[] {
            parentAccount, newA });
        
        // Check results.
        for (Integer i = 0; i < results.size(); i++) {
            if (results[i].isSuccess()) {
            System.debug('Successfully created ID: '
                  + results[i].getId());
            } else {
            System.debug('Error: could not create sobject '
                  + 'for array element ' + i + '.');
            System.debug('   The error reported was: '
                  + results[i].getErrors()[0].getMessage() + '\n');
            }
        }
    }
}

--
Thanks,
Prashant