A junction object is a custom object with two master-detail relationships, and it is the key to making a many-to-many relationship. This sentence you will find in many salesforce official knowledge articles but it doesn’t necessarily have to be just master detail relationship. You can create a junction object using lookup relationship as well.
Though a MD relationship is preferred because :
- In lookup, a child record can exist independently thereby defeating the purpose of junction object.
- No Cascade Delete
- Independent record ownership and owd.
Junction objects play a very vital role in some scenarios where we need many-to-many relationships to solve a business problem. Consider an example where we have students and sports are two objects. A sport can be played by many students and similarly a student can play multiple sports.
A many-to-many relationship is created by defining a third table which is called a junction object. In Salesforce, we can define this third table which can have the following combinations defined with the other two tables:
- Two lookup relationships
- Two Master-Detail relationships
- One lookup and one master detail relationship
Let’s take an example and see how to create junction object:
- Create an object named X.
- Created an object named Y.
- Create a junction object named Z, which will have two lookup relationships or two MD relationships with X and Y, respectively. It can also have one master-detail relationship and one lookup relationship as well.
Important Things to note :
- A junction object cannot become master object in multilevel MD relationships.
- Outbound messages not allowed.