Sub topic 6
Lookup, master-detail and many-to-many relationships
This chapter assumes you can create custom objects and fields in Object Manager. It also assumes you know the API-name conventions (__c for custom fields and objects, __r for relationship names) and the idea of a foreign key from relational databases. A relationship is a special field on one object that points to a record of another object. This chapter covers the two relationship types, how to build many-to-many links from them, and the errors that come up most often.
How relationships work
Salesforce stores a relationship as a foreign key on the child. The child object holds a field whose value is the 15- or 18-character Id of a parent record. The parent holds no field for the link. Instead, Salesforce exposes a child relationship name on the parent so you can reach the children from the parent side.
Each relationship field gives you two names:
- The field API name, such as
Account__c. This holds the Id. - The relationship name, such as
Account__r. This lets you traverse to the parent's fields in SOQL, for exampleAccount__r.Name.
There are two relationship types you create yourself: lookup and master-detail. A many-to-many relationship is not a third type. You build it from two master-detail relationships on a junction object.
Lookup relationships
A lookup is a loose link. The child record can exist without a parent, and the two records are otherwise independent.
- The lookup field is optional by default. You can mark it required.
- The child keeps its own Owner field and its own sharing. Access to the parent does not grant or restrict access to the child.
- Either side can be a standard or custom object. A custom
Invoice__ccan look up toAccount, and a lookup field on a standard object likeContactcan point to a custom object. - Roll-up summary fields are not available on a lookup parent.
- A lookup field can point to the same object, which gives you a hierarchy.
Account.ParentIdis a standard example.
You choose what happens when someone deletes the parent. This setting is called the lookup filter's sibling, the delete constraint:
| Option | Effect when the parent is deleted |
|---|---|
| Clear the value of this field | Children stay, and their lookup becomes empty. This is the default. |
| Don't allow deletion | Salesforce refuses to delete a parent that has children. |
A required lookup cannot use the clear option, because the field cannot become empty. It must use "Don't allow deletion".
Master-detail relationships
A master-detail relationship is a tight link. The parent is the master and the child is the detail. The detail record cannot exist alone.
- The master-detail field is always required on the detail record.
- The detail has no Owner field. It inherits the owner of its master. The detail object's sharing setting becomes "Controlled by Parent" (
ControlledByParentin metadata). - Deleting the master deletes all its detail records (cascade delete). Undeleting the master restores them.
- The master can have roll-up summary fields that calculate
COUNT,SUM,MINorMAXover the details. - By default, you cannot move a detail to a different master. You can allow this with the "Allow reparenting" option.
- The detail side must be a custom object. A standard object can be a master but never a detail.
- A custom object can have at most two master-detail fields. Master-detail chains can be at most three levels deep.
Here is a master-detail field for Invoice_Line__c, with Invoice__c as the master. This file would be named Invoice__c.field-meta.xml and sit under objects/Invoice_Line__c/fields/ in a Salesforce DX project.
<?xml version="1.0" encoding="UTF-8"?>
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Invoice__c</fullName>
<label>Invoice</label>
<type>MasterDetail</type>
<referenceTo>Invoice__c</referenceTo>
<relationshipLabel>Invoice Lines</relationshipLabel>
<relationshipName>Invoice_Lines</relationshipName>
<relationshipOrder>0</relationshipOrder>
<reparentableMasterDetail>false</reparentableMasterDetail>
<writeRequiresMasterRead>false</writeRequiresMasterRead>
</CustomField>The relationshipName of Invoice_Lines becomes Invoice_Lines__r in SOQL subqueries. The relationshipOrder value matters on junction objects, as described below.
A roll-up summary field on Invoice__c can then total the lines. It would be saved as Line_Total__c.field-meta.xml under objects/Invoice__c/fields/.
<?xml version="1.0" encoding="UTF-8"?>
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Line_Total__c</fullName>
<label>Line Total</label>
<type>Summary</type>
<summarizedField>Invoice_Line__c.Amount__c</summarizedField>
<summaryForeignKey>Invoice_Line__c.Invoice__c</summaryForeignKey>
<summaryOperation>sum</summaryOperation>
</CustomField>Comparing the two types
| Property | Lookup | Master-detail |
|---|---|---|
| Parent required | Optional by default | Always required |
| Child owner | Child has its own owner | Inherited from master |
| Sharing and security | Independent | Controlled by the master |
| Parent deleted | Clear the field or block deletion | Details are deleted too |
| Roll-up summary on parent | No | Yes |
| Standard object as child | Yes | No |
| Reparenting | Always allowed | Off unless enabled |
Choose master-detail when the child has no meaning without the parent, such as invoice lines on an invoice. Choose a lookup when the child has its own lifecycle, such as a case that references an account but stays after the account goes away.
Many-to-many with a junction object
Salesforce has no direct many-to-many field. You create a junction object with two master-detail fields, one to each side. Each junction record links one record from each side. Many junction records between the same two parents represent many-to-many.
Here is a course enrollment model. Course__c and Student__c are ordinary custom objects, and Enrollment__c is the junction.
Junction behavior follows from the two master-detail fields:
- The first master-detail field you create is the primary master. It decides the junction record's look and feel and, through inheritance, its owner. In metadata, this is
relationshipOrderof0. The second is1. - Deleting either master deletes its junction records. Users can see and restore them from the recycle bin along with the master.
- A user needs access to both masters to see a junction record. The more restrictive master wins.
- Both masters can have roll-up summary fields over the junction, such as the number of enrollments per course and per student.
- Junction records can carry their own fields, such as
Grade__corEnrolled_On__c.
The next anonymous Apex snippet creates one course, one student and the enrollment between them. It assumes both objects have the standard Name field.
Course__c course = new Course__c(Name = 'Data Modeling 101');
insert course;
Student__c student = new Student__c(Name = 'Priya Shah');
insert student;
Enrollment__c enrollment = new Enrollment__c(
Course__c = course.Id,
Student__c = student.Id
);
insert enrollment;Both Id values must be set. If either is missing, the insert fails with a REQUIRED_FIELD_MISSING error, because master-detail fields are required.
Querying across relationships
SOQL follows relationships in two directions. Going from child to parent uses the __r name in dot notation. You can go up to five levels. Going from parent to child uses a subquery on the child relationship name. You can go one level down per subquery.
SELECT Name, Amount__c, Account__r.Name, Account__r.Owner.Name
FROM Invoice__c
WHERE Status__c = 'Open'The parent-to-child form uses the plural child relationship name. For a custom child relationship, you add __r to it. The standard Contacts name on Account needs no suffix.
SELECT Name,
(SELECT Name, Amount__c FROM Invoice_Lines__r)
FROM Invoice__c
WHERE Status__c = 'Open'To list all students in one course, use a semi-join through the junction object. Only the Id of the other side is needed, so no join is required in the query itself.
SELECT Id, Name
FROM Student__c
WHERE Id IN (SELECT Student__c FROM Enrollment__c WHERE Course__c = :courseId)To list the enrollments with names from both sides, query the junction and traverse both parents:
SELECT Student__r.Name, Course__r.Name
FROM Enrollment__c
WHERE Course__c = :courseIdThe :courseId is an Apex bind variable. Run these queries from Apex, or replace it with a literal Id in the Developer Console.
Changing a relationship type
You can convert a lookup to master-detail and back, but both directions have preconditions.
- Lookup to master-detail: every existing child must already have a parent value in the field. Empty values block the conversion. Populate them first with a data load or a flow.
- Master-detail to lookup: you must first delete all roll-up summary fields that depend on the relationship. The child then gains an Owner field, and its sharing model changes, so review its security.
Common errors
- Duplicate relationship names. The relationship name must be unique on the parent object. If two lookups from the same child object point to the same parent, give them different child relationship names. Otherwise you cannot save the second field.
- Wrong
__rname in a subquery. The name comes from the child relationship name on the field, not the child object name. Check the field definition in Object Manager when you get "Didn't understand relationship". - Missing parent on insert. Inserting a detail with no master Id fails. Insert the master first, then use its Id.
- Row lock errors. Every insert or update of a detail record locks its master, because the roll-up summary must be recalculated. Loading many details for the same master in parallel batches can fail with
UNABLE_TO_LOCK_ROW. Order the data by master Id and use serial processing for large loads. - Cannot create a master-detail field on a populated object. If the detail object already has records, add a lookup first, fill it in, and then convert it.
- Standard object as detail. Creating a master-detail field on a standard object is not allowed. Use a lookup instead.
Exercises
Exercise
You are modeling Invoice_c and InvoiceLine__c. Lines must be deleted when their invoice is deleted, and the invoice needs a sum of line amounts. Which relationship type do you create, and which field type holds the sum?
Show answer
Create a master-detail relationship with Invoice_c as the master and InvoiceLine_c as the detail. Put a roll-up summary field with the SUM operation on Invoicec, summarizing InvoiceLine_c.Amount_c.
Exercise
A junction object Enrollment_c links Coursec and Student_c. Which master determines the owner of an enrollment record, and how many master-detail fields can the junction object have?
Show answer
The primary master, which is the first master-detail field created (relationshipOrder 0), determines the owner and look and feel. A custom object can have at most two master-detail fields, so the junction has exactly those two.
Exercise
Write a SOQL query that returns each Student__c Name along with the number of its enrollments, using the junction object.
Show answer
SELECT Student_r.Name, COUNT(Id) FROM Enrollmentc GROUP BY Studentr.Name. Alternatively, add a roll-up summary field on Studentc that counts Enrollment_c records and query that field directly.