Sub topic 11
Relationship fields and what they connect
This chapter assumes you know what an object, record and field are, and that you can create a custom field in Object Manager. It covers what a relationship field is, the five kinds you will meet, and how to read them in SOQL, Apex and metadata. The next chapter compares lookup and master-detail in depth, so this one stays on the overall model.
What a relationship field stores
A relationship field links one record to another. The field holds the Id of the record it points to. The object that holds the field is the child, and the object it points to is the parent. A Contact record has an AccountId field, so Contact is the child and Account is the parent.
The field type is REFERENCE in Apex, and the user interface shows it as a clickable link to the parent. One child record points to at most one parent through one field. Each parent can have many children. To connect two objects many-to-many, you create a junction object with two relationship fields. That pattern is in the next chapter.
The five relationship types
| Type | Child object | Parent object | Parent required | Key behavior |
|---|---|---|---|---|
| Lookup | Standard or custom | Standard or custom | No, unless you make the field required | Child keeps its own owner and sharing |
| Master-detail | Custom | Standard or custom | Yes | Child inherits owner and sharing, is deleted with the parent, and the parent can have roll-up summary fields |
| Hierarchical | User only | User | No | Links a user to another user, such as a manager |
| External lookup | Standard or custom | External object | No | Matches the child's value against the parent's external ID |
| Indirect lookup | External object | Standard or custom | No | Matches the child's external ID value against a unique field on the parent |
Lookup
A lookup is the loosest link. The child can exist without a parent, and you can make the field required if you want. Each record keeps its own owner, so sharing on the child is independent of the parent. You choose what happens when the parent is deleted. The default clears the field on the children. You can instead block the deletion while children exist.
Standard objects use lookups heavily. Contact.AccountId, Opportunity.AccountId and Case.ContactId are lookups. An object can also look up to itself, as Account.ParentId does for parent accounts.
Master-detail
A master-detail relationship ties the child's life to the parent. The parent is required on every detail record. The detail record has no Owner field and inherits owner, sharing and security from the master. Deleting the master deletes its details. This tight coupling is what allows roll-up summary fields on the master. Each custom object can have at most two master-detail fields.
Hierarchical
A hierarchical relationship is a lookup from User to User. You can add it only on the User object. A common use is a custom "Mentor" or "Delegate approver" field. Don't confuse it with a lookup from a custom object to itself, which is an ordinary lookup.
External and indirect lookups
Both types work with external objects, which Salesforce Connect exposes from data stored outside Salesforce. An external lookup lets a Salesforce record point to an external parent. An indirect lookup lets an external record point to a Salesforce parent. The Salesforce parent field must be a unique external ID field. Neither type stores a Salesforce record Id. They store a matching value.
Naming: the field and the relationship
Every relationship field has two names, and mixing them up causes many query errors.
- The field name holds the Id:
AccountId, orPrimary_Contact__cfor a custom field. - The relationship name lets you traverse to the parent's fields:
Account, orPrimary_Contact__r. A custom relationship name ends in__r. - The child relationship name lets the parent query its children. It is usually plural:
Contacts, orInvoices__rfor a custom child.
You choose the relationship name and child relationship name when you create a custom field. Pick them deliberately, because code and formulas refer to them.
Reading relationships in SOQL
Use the relationship name to move up from child to parent. Use a subquery on the child relationship name to move down.
SELECT Id, LastName, Account.Name, Account.Owner.Name
FROM Contact
WHERE Account.Industry = 'Energy'SELECT Name, (SELECT LastName, Email FROM Contacts)
FROM Account
WHERE Id IN (SELECT AccountId FROM Opportunity)SOQL can traverse up to five levels from child to parent. A subquery returns the children as a list on each parent record. A relationship field is also a normal filter field, so WHERE AccountId = :acctId works.
Seeing the field in Apex and metadata
A describe call shows how Apex sees the field, including which object it points to.
Schema.DescribeFieldResult f = Contact.AccountId.getDescribe();
System.debug(f.getType()); // REFERENCE
System.debug(f.getRelationshipName()); // Account
System.debug(f.getReferenceTo()); // a list containing the Account typeA few fields, such as Task.WhatId and Owner, are polymorphic. They can point to several object types, so getReferenceTo() returns more than one entry. Check it before assuming a single parent.
In metadata, a lookup field names its target and the delete behavior.
<?xml version="1.0" encoding="UTF-8"?>
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Primary_Contact__c</fullName>
<label>Primary Contact</label>
<type>Lookup</type>
<referenceTo>Contact</referenceTo>
<relationshipLabel>Accounts (Primary Contact)</relationshipLabel>
<relationshipName>Primary_For_Accounts</relationshipName>
<deleteConstraint>SetNull</deleteConstraint>
<required>false</required>
</CustomField>A master-detail field uses <type>MasterDetail</type> and has no deleteConstraint, because deleting the master always cascades. Its reparentableMasterDetail setting controls whether a detail record can be moved to a different master.
Common mistakes
- Querying
Account__c.Namewhen you needAccount__r.Name. The__cname is the Id, and the__rname is the parent record. - Choosing master-detail only to get roll-ups. The cost is that the parent becomes mandatory, and sharing and deletion are tied together.
- Assuming a child always has a parent. A lookup can be empty, so formulas and code that read
Account.Namemust handle null. - Ignoring existing data. Converting a lookup to master-detail requires every child record to already have a parent.
- Forgetting limits. A custom object has a cap on total relationship fields, and a cap of two on master-detail fields. Check the current limits for your edition.
Exercise
A custom object TrainingSessionc must always belong to a Coursec record, should be deleted when its course is deleted, and should share the course's visibility. Which relationship type fits? Then write the SOQL that returns each session's name and its course's name, assuming the field is Course_c.
Show answer
Master-detail fits, because the parent is required, deletion cascades and sharing is inherited. The query is: SELECT Name, Course_r.Name FROM TrainingSession_c. The traversal uses the relationship name Courser, not the field name Course_c, which holds only the Id.
Exercise
A Salesforce Contact record needs a link to a row held in an external system that you expose as an external object. Which relationship type do you use, and what does the field store?
Show answer
Use an external lookup. The field stores a value that matches the external ID of the parent external object, not a Salesforce record Id.