Junction objects for many-to-many models
Key Takeaway
To link two objects many-to-many, create a junction custom object with two master-detail relationships, one to each object. Because both links are master-detail relationships, a user's ability to create, edit, or delete a junction record depends on their sharing access to both master records.
A many-to-many relationship lets each record of one object link to many records of another object, and the reverse. You build one with a junction object, which is a custom object that sits between the two objects. The junction object holds two master-detail relationships, one to each object. Each junction record stands for one pairing. The design matters because the two master-detail relationships tie each junction record to both master records for sharing access, deletion, page appearance, and reporting.
How a junction object links two objects
A many-to-many relationship lets each record of one object link to multiple records of another object, and the reverse. For example, with a custom Bug object and the standard Case object, one bug can relate to many cases, and one case can relate to many bugs.
The two objects a junction object connects can be any two objects, such as the standard Case object and a custom Bug object. Each junction record represents a single pairing, such as one bug linked to one case. The junction object has a many-to-one relationship with each of the two objects. Together, those two links create the many-to-many relationship.
Each custom object can have up to 2 master-detail relationships and many lookup relationships, so a junction object uses both of its master-detail slots. Each relationship also counts toward the object's maximum number of custom fields.
A training company has two custom objects, Course and Instructor. One course can have several instructors, and one instructor can teach several courses. The admin creates a junction object labeled CourseInstructorAssociation with one master-detail relationship to Course and another to Instructor. Priya and Marco both teach Intro to Flow, and Priya also teaches Reports 101. The org stores three junction records: Priya with Intro to Flow, Marco with Intro to Flow, and Priya with Reports 101. Each record is one pairing. Priya's two courses come from the two junction records that point to her.