No Results
Search Tips:
- Please consider misspellings
- Try different search keywords
Newer Version Available
Accessing sObject Fields Through Relationships
sObject records represent relationships to other records with two fields: an ID and an address that points to a representation of the associated sObject. For example, the Contact sObject has both an AccountId field of type ID, and an Account field of type Account that points to the associated sObject record itself.
The ID field can be used to change the account with which the contact is associated, while the sObject reference field can be used to access data from the account. The reference field is only populated as the result of a SOQL or SOSL query (see note below).
For example, the following Apex code shows how an account and a contact can be associated with one another, and then how the contact can be used to modify a field on the account:
1Account a = new Account(Name = 'Acme');
2insert a; // Inserting the record automatically assigns a
3 // value to its ID field
4Contact c = new Contact(LastName = 'Weissman');
5c.AccountId = a.Id;
6// The new contact now points at the new account
7insert c;
8
9// A SOQL query accesses data for the inserted contact,
10// including a populated c.account field
11c = [SELECT Account.Name FROM Contact WHERE Id = :c.Id];
12
13// Now fields in both records can be changed through the contact
14c.Account.Name = 'salesforce.com';
15c.LastName = 'Roth';
16
17// To update the database, the two types of records must be
18// updated separately
19update c; // This only changes the contact's last name
20update c.Account; // This updates the account nameIn addition, the sObject field key can be used with insert, update, or upsert to resolve foreign keys by external ID. For example:
1Account refAcct = new Account(externalId__c = '12345');
2
3Contact c = new Contact(Account = refAcct, LastName = 'Kay');
4
5insert c;This inserts a new contact with the AccountId equal to the account with the external_id equal to ‘12345’. If there is no such account, the insert fails.