[SalesForce] Insert Parent and Child Objects of One Type within One DML statement

I want to insert Parent and Child Accounts in one DML statement.
I know it can be done for related Contact/Account objects using External Id field, but it doesn't work in my case.

Running the following code

Account childAccount = new Account(Name='Child Account');
Account parentAccountRef = new Account(External_Id__c='123');
childAccount.Parent = parentAccountRef;
Account parentAccount = new Account(Name='Parent Account', External_Id__c='123');

Database.insert(new Account[] {parentAccount, childAccount});

I get the error:

System.DmlException: Insert failed. First exception on row 1; first
error: INVALID_FIELD, Foreign key external ID: 123 not found for field
External_Id__c in entity Account: []

Best Answer

This approach only works with different types. Take a look at Creating Parent and Child Records in a Single Statement Using Foreign Keys (emphasis mine):

You can use external ID fields as foreign keys to create parent and child records of different sObject types in a single step instead of creating the parent record first, querying its ID, and then creating the child record.

...

You can create related records that are up to 10 levels deep. Also, the related records created in a single call must have different sObject types. For more information, see Creating Records for Different Object Types in the SOAP API Developer's Guide.