Sub topic 9
Junction Objects: A Child of Two Parents
This chapter assumes you know how to create custom objects and fields in Setup, and that you understand the difference between a lookup and a master-detail relationship. It covers what a junction object is, why Salesforce needs one, and how it behaves. The next chapters build one step by step.
The problem: one field points to only one parent
A relationship field on a record holds the Id of exactly one parent record. That is enough for one-to-many data. One Account has many Contacts, and each Contact points to one Account.
Many-to-many data does not fit this model. Consider a training company:
- A course has many students.
- A student takes many courses.
If you put a Student__c field on Course, each course can name only one student. If you put a Course__c field on Student, each student can name only one course. Neither side can hold the full answer, and a multi-select picklist or a text list would lose the relationship features: queries, reports, security, and referential integrity.
What a junction object is
A junction object is a custom object that has two master-detail relationships, each to a different parent object. Each record of the junction object links one record from the first parent to one record from the second parent.
In the training example, Enrollment__c is the junction object:
Course__cis a master-detail field to Course.Student__cis a master-detail field to Student.- Each Enrollment record says "this student is enrolled in this course".
Course and Student are the parents (masters). Enrollment is the child (detail) of both. Salesforce has no separate many-to-many field type. A many-to-many relationship is two one-to-many relationships that share a child object.
Why the junction object uses master-detail
Both relationship fields on a junction object must be master-detail. This gives the junction record several properties.
- Each parent is required. An Enrollment cannot exist without a Course and a Student. A link that points to nothing is not a valid link.
- Deleting a parent deletes its junction records. If you delete a Course, its Enrollment records are deleted too. The Student records stay, because Student is a different parent.
- Sharing is inherited. Access to an Enrollment comes from its parents (the next section and later chapters cover which parent controls what).
- Roll-up summary fields work on both parents. Course can count its Enrollments, and Student can do the same.
Because the junction record has no meaning without both parents, these rules keep the data consistent without extra code.
The junction object has no owner
A detail record in a master-detail relationship does not have its own Owner field. Its owner and sharing come from the master. A junction object has two masters, so Salesforce uses the primary master to decide this. Other chapters in this tutorial describe primary and secondary masters in detail. For now, remember that the first master-detail field you create on the junction object becomes the primary master.
Deletion behavior in practice
Deletion has several edge cases worth knowing.
| Action | Result |
|---|---|
| Delete a Course | The Course's Enrollment records are deleted with it (moved to the Recycle Bin). Students are not affected. |
| Delete a Student | The Student's Enrollment records are deleted. Courses are not affected. |
| Delete a single Enrollment | Only that link is removed. Both parents remain. |
| Undelete a Course | The Enrollment records deleted with it are restored, provided the other parent still exists. |
Undelete is the subtle case. Suppose you delete a Course, and then delete a Student who was enrolled in it. You then undelete the Course. The Enrollment for the deleted Student cannot be restored, because its other parent is gone. Restore the Student first if you need the link back.
Junction objects and the two-field limit
A custom object can have at most two master-detail relationships. A junction object uses both. This has consequences:
- You cannot add a third master-detail field to Enrollment, for example to link to an Instructor. A third relationship has to be a lookup.
- A junction object cannot be the master in another master-detail relationship in the usual way that would break the limit on nesting. Roll-up summary fields still work on the parents, but you cannot build deep chains of master-detail relationships without limits. Salesforce supports a limited number of levels, so check the current limits before you design a chain.
- Standard objects cannot be the detail side of a master-detail relationship. A junction object must therefore be a custom object. The parents can be standard or custom, with some exceptions for standard objects that cannot be masters. For example, you can have a junction between Contact and a custom object.
Defining the field in metadata
The metadata for a master-detail field shows the settings that matter for a junction object. This file defines the field from Enrollment__c to Course__c.
<?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 control the behavior:
typeisMasterDetail, which makes the parent required and enables cascade delete.referenceTonames the parent object.relationshipNameis the name you use in a parent-to-child SOQL subquery. Salesforce adds the__rsuffix when you query it.relationshipOrderis0for the primary master. The second master-detail field on the same object uses1.reparentableMasterDetailset tofalsemeans an existing Enrollment cannot be moved to a different Course. Set it totrueif users need to change the parent.
Reading and writing junction records
Once both parents exist, you create a junction record by supplying both parent Ids. Both parents must be inserted first, because each master-detail field requires an Id.
Course__c course = new Course__c(Name = 'Apex Basics');
Student__c student = new Student__c(Name = 'Ada Lovelace');
insert course;
insert student;
insert new Enrollment__c(Course__c = course.Id, Student__c = student.Id);To read the students of a course, you go through the junction object. The inner query reads the child relationship from Course and then follows Student__r to the other parent.
SELECT Name, (SELECT Student__r.Name FROM Enrollments__r)
FROM Course__c
WHERE Name = 'Apex Basics'The relationship name in the subquery must match the child relationship name defined on the field, with the __r suffix. If your field was created with the relationship name Enrollments, the subquery uses Enrollments__r. If a query fails with an invalid relationship error, check the name on the field definition first.
Common design mistakes
- Creating the object with a lookup first. If you add a lookup and later need master-detail, conversion is possible only when every existing record has a value in the field. Plan the model before loading data.
- Using two lookups instead. Two lookups also link two parents, but you lose cascade delete, required parents, inherited sharing, and roll-up summaries. Choose this only when the link must be optional.
- Allowing duplicate links. Salesforce does not stop a user from creating two Enrollment records for the same student and course. If duplicates matter, enforce uniqueness with a duplicate rule, a unique text field, or a trigger.
- Ignoring which parent is primary. The primary master decides ownership and sharing for the junction record. Choose the order deliberately.
- Storing extra data in the wrong place. Facts about the link itself, such as the enrollment date or grade, belong on the junction object. Facts about only the course or only the student belong on those objects.
Summary of the model
Exercise
A team has Course_c and Studentc objects. They create Enrollmentc with a lookup to Coursec and a lookup to Student_c. A user deletes a Course. What happens to the Enrollment records for that course, and what would change if both fields were master-detail?
Show answer
With lookups, the Enrollment records stay, and their Course__c field is cleared by default (or the delete is blocked if the lookup is configured that way). With two master-detail fields, the Enrollment records for the deleted Course are deleted with it. The master-detail version also makes both parents required, lets Course and Student have roll-up summary fields over Enrollment, and makes Enrollment inherit its sharing from its parents.
Exercise
You need to find every student in the course named 'Apex Basics'. Which object do you query, and which relationship do you follow?
Show answer
Query Course_c, filter on Name = 'Apex Basics', and use a subquery on the child relationship from Course to the junction object (Enrollmentsr). Inside the subquery, select Studentr.Name to reach the other parent. For example: SELECT Name, (SELECT Studentr.Name FROM Enrollmentsr) FROM Course_c WHERE Name = 'Apex Basics'.
Exercise
Why must both parent records be inserted before the junction record in Apex?
Show answer
Each master-detail field on the junction object is required, and it takes the Id of a parent record. A record that has not been inserted has no Id yet, so the Enrollment insert would fail without both parent Ids.