Many-to-Many Relationships with Junction Objects
By the end of this lesson, you'll be able to:
- Explain why a junction object is needed to model a many-to-many relationship
- Design a junction object connecting two existing objects
Prerequisites: Lookup vs. Master-Detail Relationships
Why a junction object
Salesforce relationships are fundamentally one-to-many — a lookup or master-detail always has exactly one parent per child. To represent "many Students can enroll in many Courses," you introduce a junction object — e.g. Enrollment__c — with a master-detail to Student__c and a second master-detail to Course__c, one Enrollment record per Student-Course pairing.
Designing a junction object
The junction object commonly also carries data specific to that pairing — e.g. Enrollment__c might have an EnrollmentDate__c or Grade__c field that belongs to neither Student nor Course alone, only to their combination. This is often the natural place such data belongs anyway.
Querying through a junction object
-- One row per Student-Course pairing
SELECT Id, Student__c, Course__c, EnrollmentDate__c
FROM Enrollment__c
WHERE Course__c = :courseId
Each Enrollment__c row represents one specific Student enrolled in one specific Course — querying by Course__c returns every Student enrolled in it via this junction.
Exercise
Design a junction object to model 'many Employees can work on many Projects.' Name the junction object and its two master-detail relationships.
Show hint
The junction needs a master-detail to Employee and a master-detail to Project.
Many-to-Many Relationships with Junction Objects — Quick Check
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
Salesforce has no native many-to-many relationship — you model one with a junction object, a custom object with two master-detail (or lookup) relationships, one to each side of the many-to-many.