Sub topic 4
Master-detail relationships: tightly coupled records
This chapter assumes you know how to open Setup and the Object Manager, and that you can read a basic SOQL SELECT. It also assumes you have met the terms parent, child, and relationship field. The previous chapter covered lookup relationships. Here you will see how a master-detail relationship changes the rules.
What master-detail means
A master-detail relationship is a relationship field on a child object. The field points to a parent object. The parent is the master and the child is the detail. The field looks like a lookup, but the two records are bound together:
- The detail record cannot exist without a master. The relationship field is always required.
- Deleting the master deletes its detail records.
- The detail record has no owner of its own. It takes its ownership and sharing from the master.
- The master object can define roll-up summary fields that calculate values from its details.
Use master-detail when the child has no meaning on its own. A line item without an invoice is one example. A course enrollment without a course is another.
Behavior at a glance
| Area | Behavior on the detail record |
|---|---|
| Master value | Required. You cannot save a detail record without a master. |
| Deleting the master | All of its detail records are deleted too. |
| Deleting a detail | Only that detail is deleted. The master is not affected. |
| Owner | There is no Owner field. The master's owner applies. |
| Sharing | Access follows the master. You cannot create sharing rules on the detail object. |
| Roll-up summary | Available on the master object. |
| Changing the master | Blocked unless you allow reparenting on the field. |
Creating the relationship in Setup
- In Setup, open Object Manager and choose the detail object, for example
Enrollment__c. - Open Fields & Relationships and click New.
- Choose Master-Detail Relationship as the data type and click Next.
- Choose the master object, for example
Course__c, and click Next. - Enter the field label. The API name is generated from it and ends in
__c. - Choose the sharing setting for the field. This is the "Allow users with read access to master..." option, explained below.
- Optionally set a lookup filter. Then choose the field-level security and page layouts, and save.
- On the master object's page layout, check the related list that was added. Its label comes from the relationship label you entered.
Two things can surprise you here. First, you can only pick a master from objects that are allowed to be one. A custom object can be a master. Many standard objects, such as Account, can also be masters of custom detail objects. A standard object cannot be the detail side of a master-detail relationship. Second, the related object cannot be changed once the field exists. To point at a different master object you must create a new field.
The field as metadata
If you work with source-tracked projects, the field is a CustomField file in the detail object's folder. This is the field from the course example:
<?xml version="1.0" encoding="UTF-8"?>
<!-- force-app/main/default/objects/Enrollment__c/fields/Course__c.field-meta.xml -->
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Course__c</fullName>
<label>Course</label>
<referenceTo>Course__c</referenceTo>
<relationshipLabel>Enrollments</relationshipLabel>
<relationshipName>Enrollments</relationshipName>
<relationshipOrder>0</relationshipOrder>
<reparentableMasterDetail>false</reparentableMasterDetail>
<type>MasterDetail</type>
<writeRequiresMasterRead>false</writeRequiresMasterRead>
</CustomField>These elements matter for this chapter:
typeset toMasterDetailmakes the field master-detail. A lookup usesLookup.referenceTonames the master object.relationshipNameis the child relationship name. SOQL uses it in parent-to-child subqueries. Apex and SOQL append__rfor custom relationships, so this one is used asEnrollments__r.relationshipOrderis0for the first master-detail field on an object. It is1for a second one. Chapter 11 covers what this order controls.reparentableMasterDetaildecides whether a detail can be moved to a different master after it is created.writeRequiresMasterReadcontrols the sharing setting from step 6.
Reparenting
With reparentableMasterDetail set to false, the master is fixed when the detail is created. An update that changes the field fails. Set it to true when users must be able to correct a wrong master. This is the Allow reparenting checkbox in Setup. Reparenting a detail changes who can see it, because the detail follows its new master's owner and sharing. Plan for that before you enable it.
The write-access setting
By default (writeRequiresMasterRead is false), a user needs read and edit access to the master to create, edit, or delete its detail records. If you set it to true, read access to the master is enough. Choose true when many users should add details to records they cannot edit. An example is a support agent adding a line item to an order owned by someone else.
Cascade delete
Deleting a master record moves its detail records to the Recycle Bin with it. This also fires delete logic on the details, such as triggers. Deleting a detail has no effect on the master.
Undelete works in the other direction. Restoring a master restores the details that were deleted with it. A detail that was deleted on its own can be restored while its master still exists. You cannot restore a detail whose master is in the Recycle Bin. Restore the master first.
Cascade delete is the main danger of this relationship type. A user who has permission to delete a master can remove thousands of detail records with one click. Check the delete permission on master objects before you grant it widely.
Ownership and sharing
A detail object has no OwnerId field. You cannot set an owner in Apex, in a data load, or in the page layout. Access to a detail record is decided by the master:
- A user who can see the master can see its details, and a user who cannot see the master cannot see its details.
- The detail object's organization-wide default is shown as Controlled by Parent.
- You cannot create owner-based or criteria-based sharing rules on the detail object. Share the master instead.
- Transferring the master to a new owner moves the access for all its details along with it.
If a record needs its own owner, its own sharing rules, or its own visibility, a master-detail relationship is the wrong fit. Use a lookup.
Limits and restrictions
- A custom object can have at most two master-detail fields. Chapters 9 to 11 use both of them to build a junction object.
- Master-detail chains can run to a limited depth. A detail object can itself be the master of another object, up to three levels in total.
- A standard object can be a master but cannot be a detail.
- A master-detail field cannot be left blank, so any new field of this type needs a value on every existing record. When you add one to an object that already has data, Salesforce cannot fill in a master for you. Create it as a lookup first, populate it, and then convert it. Chapter 8 covers conversion in detail.
- The master object gets related lists and roll-up summary fields. The detail object does not get fields from its master. To read master data you traverse the relationship in SOQL, in formulas, or in Apex.
Working with details in code
A detail needs a master Id at insert time. This Apex example assumes an Invoice__c master and an Invoice_Line__c detail with a master-detail field named Invoice__c:
Invoice__c invoice = new Invoice__c(Name = 'INV-1001');
insert invoice;
Invoice_Line__c line = new Invoice_Line__c(
Name = 'Consulting hours',
Invoice__c = invoice.Id
);
insert line;
// A detail without a master fails.
try {
insert new Invoice_Line__c(Name = 'Orphan line');
} catch (DmlException e) {
System.debug(e.getDmlStatusCode(0)); // REQUIRED_FIELD_MISSING
}
// Deleting the master also deletes the line.
delete invoice;
System.debug([SELECT COUNT() FROM Invoice_Line__c WHERE Id = :line.Id]); // 0The query at the end returns 0 because the delete cascaded. The Recycle Bin still holds the deleted line, and a query with ALL ROWS would show it.
Reading a master-detail relationship in SOQL works the same way as for a lookup. Use dot notation from the detail to the master. Use a subquery on the child relationship name from the master to its details:
SELECT Name, (SELECT Name FROM Invoice_Lines__r)
FROM Invoice__cThe child relationship name here is Invoice_Lines. Chapter 12 covers relationship queries in more detail.
Roll-up summary fields
A master-detail relationship is what lets the master object define a roll-up summary field. Such a field calculates a value from the detail records and updates itself when details are added, changed, or deleted. The supported roll-up types are COUNT, SUM, MIN, and MAX. The next chapters cover them in full. Lookup relationships cannot have native roll-up summary fields.
Common mistakes
- Treating a required field as optional. You cannot make a master-detail field optional. If some child records must exist without a parent, use a lookup.
- Forgetting that users need master access. A user who cannot see or edit the master may not be able to create or edit details. Check the write-access setting first when users report that they cannot add records.
- Granting delete on the master too widely. The delete cascades to every detail.
- Expecting an owner on the detail. Reports, list views, and assignment rules that rely on the detail's owner will not work. Use the master's owner instead.
- Enabling reparenting without thinking about sharing. Moving a detail also changes who can see it.
Exercise
A user can see an Invoice__c master record but gets an error when adding an Invoice_Line__c detail. The user has Read access to the master but not Edit. The master-detail field has writeRequiresMasterRead set to false. What setting change lets the user add the line, and what does it change?
Show answer
Set writeRequiresMasterRead to true. In Setup, this is the checkbox "Allow users with read access to master to create, edit, or delete detail records" on the field. With false, a user needs read and edit access to the master to create details. With true, read access to the master is enough.
Exercise
You delete a Course__c master record that has five Enrollment__c detail records. Which records are deleted, and can you restore one Enrollment__c record on its own while the course is still in the Recycle Bin?
Show answer
The course and all five enrollments are deleted, because delete cascades from master to detail. You cannot restore a single enrollment while its master is in the Recycle Bin. Restore the course first. Restoring the master also restores the details that were deleted with it.