Sub topic 10
Building a many-to-many relationship step by step
This chapter assumes you can create custom objects and fields in Object Manager and know what a master-detail field is. You will build a Course and Student model where a student can take many courses and a course can have many students.
The model
Salesforce has no native many-to-many field. You build one with a third object, the junction object, that holds two master-detail fields. Each junction record links one course to one student.
Steps
- Create the two parent objects,
Course__candStudent__c. Each needs only a Name field for this example. - Create the junction object
Enrollment__c. Its Name can be an auto-number so users never type one. - On
Enrollment__c, create a Master-Detail Relationship field toCourse__c. Because it is the first one, Salesforce makes Course the primary master. - Create a second Master-Detail field to
Student__c. This one becomes the secondary master. - Add the Enrollments related list to the Course and Student page layouts so users can see the links.
The first field, as it appears in source format, 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>The Student field uses the same structure with referenceTo set to Student__c and relationshipOrder set to 1. Its relationship label and name can also be Enrollments, because they are scoped to the parent object.
Why the order of creation matters
The relationshipOrder value records which master is primary (0) and which is secondary (1). Primary and secondary masters affect ownership, sharing, and what happens when a parent is deleted. The next chapter covers those differences, so for now create the field you consider the main parent first.
Creating and reading records
Both parents must exist before you insert a junction record, because each master-detail field is required:
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 list the students of a course, query the junction records as a subquery and reach through to the second parent:
SELECT Name, (SELECT Student__r.Name FROM Enrollments__r)
FROM Course__c
WHERE Name = 'Apex Basics'Common errors
- Adding master-detail to an object that already has records. Salesforce will not let you add a required parent when existing rows have no value. Create the field as a lookup, fill it on every record, then convert it to master-detail.
- Inserting a junction record without both parents. The insert fails with a required-field error. Check that both Ids are set.
- Expecting duplicate protection. Nothing stops two
Enrollment__crecords with the same course and student. Add a validation rule, a duplicate rule, or a unique text field built from both Ids if you need uniqueness. - Wrong relationship name in a query. The child relationship name in SOQL is the
relationshipNameplus__r, soEnrollmentsbecomesEnrollments__r. Check it under the field's details in Object Manager.
Exercise
You need to add a master-detail field to an existing object that already contains 5,000 records, and the field has no values yet. What steps let you do it?
Show answer
Create the field as a lookup relationship, populate the lookup on all 5,000 records (for example with a data load), then convert the field to master-detail. Master-detail fields are required, so the conversion is blocked while any record has an empty value.