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.
To do this:
• Create the child sObject and populate its required
fields, and optionally other fields.
• Create the parent reference sObject used only for
setting the parent foreign key reference on the child sObject. This sObject has only the external ID field
defined and no other fields set.
• Set the foreign key field of the child sObject to
the parent reference sObject you just created.
• Create another parent sObject to be passed to the insert statement. This sObject must
have the required fields (and
optionally other fields) set in addition to the external ID field.
• Call insert by passing it an array of sObjects to create. The
parent sObject must precede the child sObject in the array,that is, the array index of the
parent must be lower than the child’s index.
contact co = new
contact(lastName='raja');
// Create the parent reference.
// Used only for foreign key reference
// and doesn't contain any other fields.
Account accountReference = new
Account(SLASerialNumber__c='00000');
co.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',SLASerialNumber__c='47700');
// Create the account and the opportunity.
Database.SaveResult[] results = Database.insert(new SObject[]
{parentAccount, co});
// 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');
}
}
No comments:
Post a Comment