π Read Β· 20 XP
Many-to-many with junction objects
Many-to-many with junction objects
A Student takes many Courses and a Course has many Students. Relational databases solve this with a join table, and Salesforce does exactly the same thing, calling it a junction object.
Contact (student) βββM-Dββ Enrollment__c ββM-DβββΊ Course__c
Enrollment__c has two master-detail fields:
Contact__cβ ContactCourse__cβ Course__c
Each Enrollment record links one student to one course, and it can hold its own data: Status__c, Grade__c, Enrolled_On__c.
Why master-detail on both sides?
- Deleting a Course cleans up its Enrollments automatically
- You get roll-ups on both parents: "number of students" on Course, "courses taken" on Contact
- Sharing is inherited, so nobody can see an Enrollment without access to its parents
The primary master
The first master-detail field you create is the primary relationship. It decides:
- Who "owns" the junction record for sharing purposes
- The look and feel (tab style) of the junction object
Querying it
// all courses a student is enrolled in
SELECT Course__r.Name, Status__c
FROM Enrollment__c
WHERE Contact__c = :studentId
You'll build exactly this in the boss fight at the end of this chapter.