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
reddy ginnereddy ginne 

Creating Parent and Child Records in a Single Statement Using Foreign Keys

I can't see the records in my org when I write this apex class
Can anyone exaplain me why this is not inserting records in my org plz.
public class ParentChildSample {
    public static void InsertParentChild() {
        Date dt = Date.today();
        dt = dt.addDays(7);
        Opportunity newOpportunity = new Opportunity(
            Name='OpportunityWithAccountInsert',
            StageName='Prospecting',
            CloseDate=dt);
        
        // Create the parent reference.
        // Used only for foreign key reference
        // and doesn't contain any other fields.
        Account accountReference = new Account(
            MyExtID__c='SAP111111');                
        newOpportunity.Account = accountReference;
        
        // Create the Account object to insert.
        // Same as above but has 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, newOpportunity });
        
        // 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');
            }
        }
    }
}
BalajiRanganathanBalajiRanganathan
check the debug log for what errors you are getting. I assume you might need to set some required field you might have added to Account Or Opportunity. the debug log should give you what is going on here.
reddy ginnereddy ginne
I can see success in debug log but no luck.
YuchenYuchen
So in the debug log, you can see it is printing "Successfully created ID:"? Then what is the ID that is created? You can directly asscess that ID to view the record.
reddy ginnereddy ginne
I can't see id in Debug log please.
YuchenYuchen
Your code looks good it is weird that it is printing success without inserting the records.

Maybe you can add more debug logs to print the parentAccount and newOpportunity. Or you can insert these two Objects separately that should always work.

Reference link: http://www.salesforce.com/us/developer/docs/dbcom_apex250/Content/apex_dml_insert.htm