A better way to populate lookup-relationship for sets of related records
Let’s take a look at a common task when you need to create sets of related records in a single transaction. Usually, you either build child records after you already committed parent records, or have some sort of a parent-child “mapping”:
//standard approach for simple 1:1 child-to-parent relationship case
List<Account> accounts = buildAccounts();
List<Contact> contacts = buildContacts(accounts);insert accounts;//when you eventually need to populate a lookup - you're gonna need a "mapping" in place
// which in this case is a contract that Accounts and Contacts are in the same order in their respective lists
for (Integer i = 0, n = accounts.size(); i < n; i++)
{
//associating child with parent
contacts.get(i).AccountId = accounts.get(i).Id;
}insert contacts;
A better way to do it is to use a corresponding relationship field to hold a pointer to a parent record, which provides you with the seamless child-to-parent “mapping” and is available on a child record itself when you need it:
//better approach for a child-to-parent relationship task
List<Account> accounts = buildAccounts();//somewhere inside buildContacts method you're just using lookup relationship field like this
//contactRecord.Account = accountRecord;
List<Contact> contacts = buildContacts(accounts);insert accounts;//and when you eventually need to populate lookup field, you already have everything you need
for (Contact each : contacts)
{
//populating lookup field
each.AccountId = each.Account.Id;
}insert contacts;