Sub topic 3
Building a Many-to-Many Relationship Step by Step
Assume you know Salesforce objects, fields, records, Object Manager, and basic SOQL. A many-to-many relationship lets each record in one object relate to many records in another object, and vice versa.
Building a many-to-many relationship
Salesforce models this pattern with a junction object. A junction object is a custom object with two master-detail relationship fields. Each junction record connects one record from each parent object.
For example, a course can have many students, and a student can attend many courses:
Create these objects and fields:
- Create
Course__c. - Create
Student__c. - Create
Enrollment__c. - Add a required master-detail field from
Enrollment__ctoCourse__c. - Add a second required master-detail field from
Enrollment__ctoStudent__c.
The two parent records must exist before you create an enrollment.
Primary and secondary master
The first master-detail field is the primary master. The second is the secondary master. On a junction object, the primary master controls ownership and sharing for the junction record. The relationship order in metadata identifies it: 0 is primary and 1 is secondary.
Both relationships still provide parent links, and deleting either parent can delete related junction records. Configure deletion behavior carefully because this can remove connection data.
Reading related data with SOQL
Use a child relationship subquery to find students for a course. The child relationship name is configured on the master-detail field and often ends in __r.
SELECT Name, (SELECT Student__r.Name FROM Enrollments__r)
FROM Course__c
WHERE Name = 'Apex Basics'Here, Student__r.Name follows the second relationship from each enrollment to its student.
Creating junction records in Apex
Insert both parents first, then insert the junction record with both parent Ids.
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
);Exercise
What records must exist before inserting an Enrollment__c record?
Show answer
The Course_c and Student_c parent records must exist so their Ids can populate both master-detail fields.