Sub topic 10
Building a many-to-many relationship step by step
This chapter assumes you know how to create custom objects and fields in Setup or Object Manager. It also assumes you know the difference between lookup and master-detail fields, which earlier chapters cover. You will build a small training-course model in which a student can enroll in many courses and a course can have many students.
The target model
Salesforce has no direct many-to-many field. You build the relationship with a third object, a junction object, which is a child of both parents. Each record on the junction object links one course to one student.
The build order matters, so follow the steps in sequence:
- Create the two parent objects.
- Create the junction object.
- Add the first master-detail field.
- Add the second master-detail field.
- Expose the relationship on page layouts.
- Test with real records.
Step 1: Create the parent objects
Create two custom objects:
| Setting | Course | Student |
|---|---|---|
| Label | Course | Student |
| Plural label | Courses | Students |
| Record name | Course Name (text) | Student Name (text) |
| API name | `Course__c` | `Student__c` |
Both objects can be ordinary custom objects with default sharing. They don't need any special settings, because the junction object takes on their sharing behavior, not the other way around.
Step 2: Create the junction object
Create a third custom object named Enrollment (Enrollment__c). Use these settings:
- Record name: Choose Auto Number with a format such as
ENR-{0000}. A junction record rarely has a meaningful name of its own, and an auto number avoids asking users to type one. - Allow Reports: Select it, because most enrollment data is analyzed in reports.
- Deployment status: Set it to Deployed once you are ready to test.
Don't add an Owner field or choose a sharing model. A custom object that has a master-detail field gets its sharing model set to Controlled by Parent, and the object has no owner of its own.
Step 3: Add the first master-detail field
On Enrollment, create a new field of type Master-Detail Relationship that points to Course. Set the field label to Course and the child relationship name to Enrollments. In the wizard you will also choose the related-list label, which is the heading users see on the Course page.
The first master-detail field you create on a junction object becomes its primary master. Salesforce records this as relationshipOrder 0 in metadata. The next chapter explains what the primary master controls, so this chapter only sets the order correctly.
If you manage the org with source-tracked metadata, the field looks like this:
<?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>Two properties in this file deserve attention:
reparentableMasterDetailset tofalsemeans a user cannot change an existing enrollment to point to a different course. Set it totrueif you want to allow moving a junction record to another parent.writeRequiresMasterReadset tofalsemeans a user needs only Read access on the parent to create or edit junction records. Setting it totruerequires Read access on the parent record and is a stricter option.
Step 4: Add the second master-detail field
Create a second Master-Detail Relationship field on Enrollment that points to Student. Because a primary master already exists, Salesforce treats this field as the secondary master. Its relationshipOrder is 1.
<?xml version="1.0" encoding="UTF-8"?>
<!-- force-app/main/default/objects/Enrollment__c/fields/Student__c.field-meta.xml -->
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Student__c</fullName>
<label>Student</label>
<referenceTo>Student__c</referenceTo>
<relationshipLabel>Enrollments</relationshipLabel>
<relationshipName>Enrollments</relationshipName>
<relationshipOrder>1</relationshipOrder>
<reparentableMasterDetail>false</reparentableMasterDetail>
<type>MasterDetail</type>
<writeRequiresMasterRead>false</writeRequiresMasterRead>
</CustomField>Both fields use the relationship name Enrollments. That is allowed because each name belongs to a different parent object. A SOQL query traverses it as Enrollments__r.
The junction object itself needs ControlledByParent as its sharing model. Deploy it together with the fields, because the platform validates that setting against the master-detail fields:
<?xml version="1.0" encoding="UTF-8"?>
<!-- force-app/main/default/objects/Enrollment__c/Enrollment__c.object-meta.xml -->
<CustomObject xmlns="http://soap.sforce.com/2006/04/metadata">
<label>Enrollment</label>
<pluralLabel>Enrollments</pluralLabel>
<nameField>
<label>Enrollment Number</label>
<type>AutoNumber</type>
<displayFormat>ENR-{0000}</displayFormat>
<startingNumber>1</startingNumber>
</nameField>
<deploymentStatus>Deployed</deploymentStatus>
<sharingModel>ControlledByParent</sharingModel>
<enableReports>true</enableReports>
</CustomObject>Step 5: Add useful fields and layouts
A junction object is the natural place to store data about the link itself. A student's status in a course is a fact about the pair, not about the student or the course. Add fields such as these to Enrollment:
Status__c, a picklist with values such as Enrolled, Completed, and Withdrawn.Enrollment_Date__c, a date field.Final_Grade__c, a number or picklist field.
Then check the page layouts:
- Open the Course page layout and confirm that an Enrollments related list appears. Add the Student, Status, and Enrollment Date columns to it.
- Open the Student page layout and do the same, with Course in place of Student.
- Open the Enrollment page layout and confirm that both Course and Student are on it. Both fields are required, so Salesforce adds them for you.
Related lists on the two parents give users the many-to-many view in both directions. A user on a course sees its students, and a user on a student sees their courses.
Step 6: Test with real records
Create one course and two students in the UI. On the course page, click New in the Enrollments related list and choose a student. Repeat for the second student, and then open the first student and add a second course. When you open each parent, the related list should show the enrollments that apply to it.
Now test the deletion behavior:
- Delete one enrollment. Neither the course nor the student is affected.
- Delete a student. Salesforce deletes that student's enrollments, because the junction records cannot exist without both parents.
- Undelete the student from the Recycle Bin. The enrollments come back as well, as long as the other parent still exists.
You can also build the same records in code. Both parents must exist before the junction record is inserted, because each master-detail field needs a parent 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 check the result, query the course and go through the junction records to the students:
SELECT Name, (SELECT Student__r.Name FROM Enrollments__r)
FROM Course__c
WHERE Name = 'Apex Basics'Later chapters cover this query syntax and the Apex DML in more depth.
Common errors and design gotchas
The same pair can be enrolled twice
Salesforce does not stop you from creating two Enrollment records with the same course and student. Nothing in the two master-detail fields enforces uniqueness. If duplicates matter, choose one of these approaches:
- Add a text field with the Unique and Case sensitive options turned on. Fill it with the combined Ids of the two parents through a record-triggered flow or an Apex trigger, and the platform rejects a second record with the same value.
- Check for an existing pair in a before-save flow or trigger, and add an error to the record.
A user cannot add records to a parent they cannot see
With writeRequiresMasterRead set to false, a user needs Read access to both parents, and also needs to be able to create records on Enrollment through their profile or permission set. If the New button is missing from a related list, check the object permissions on Enrollment first, then check sharing on the parent records.
Sharing follows the masters
Because Enrollment has no owner, a user's access to an enrollment comes from the two parents. The next chapters explain how primary and secondary masters shape that access. When you test, always log in as a non-administrator, because System Administrators can see everything and hide sharing problems.
Roll-up summaries sit on the parents
Each parent can have roll-up summary fields over its enrollments. For example, Course can have a count of enrollments, and Student can have a count of completed courses, filtered by Status__c. These fields work because both fields are master-detail. A lookup would not support them.
Summary of the build
| Step | What you create | Result |
|---|---|---|
| 1 | `Course__c` and `Student__c` | The two parents |
| 2 | `Enrollment__c` with an auto number name | The junction object, controlled by its parents |
| 3 | `Course__c` master-detail field, order 0 | Primary master |
| 4 | `Student__c` master-detail field, order 1 | Secondary master |
| 5 | Extra fields and related lists | Data about the link, visible from both sides |
| 6 | Test records | Confirmed behavior for create and delete |
Exercise
You have already created Enrollment_c and its master-detail field to Coursec. A teammate then adds the master-detail field to Student_c. Which field is the primary master, which relationshipOrder values do the two fields have, and what happens to the enrollments of a student who is deleted?
Show answer
The field to Course_c is the primary master because it was created first, so its relationshipOrder is 0. The field to Student_c is the secondary master, with relationshipOrder 1. When a student is deleted, Salesforce also deletes that student's Enrollment records, because a junction record cannot exist without both parents. The course is not affected, and undeleting the student restores the enrollments.
Exercise
Your org must prevent the same student from being enrolled twice in the same course. The two master-detail fields do not do this. Name one way to enforce it.
Show answer
Add a text field on Enrollment__c marked Unique and Case sensitive, and fill it with the course Id and student Id joined together, using a record-triggered flow or an Apex trigger. A second enrollment for the same pair gets the same value, so the platform rejects it. Another valid answer is a before-save flow or trigger that looks for an existing pair and adds an error to the record.