Creating relationships
In our movie example, we have our Movie object and we have our Person object. To create a many-to-many relationship between both, we need a junction object. As I mentioned previously, we will be using Cast as a junction object. So, let's create that junction object and see why we did that:
- Navigate to Setup | Object Manager.
- Create a new custom object with the following details:
- Label: Cast
- Plural: Cast
- Record Name: Role Name
- Type: Text
- Allow Search: true
- Leave the other defaults as is
- Now, create a new custom field:
- Type: Master-Detail Relationship
- Related to: MOVIE
- Label: Movie
- Field Name: Movie
- Child Relationship Name: Cast
- Leave all other defaults and click next, next, save
- Create the second custom field with following details:
- Type: Master-Detail Relationship
- Related to: PERSON
- Label: Person
- Field Name: Person
- Child Relationship Name: Cast
- Leave all other defaults and click next, next, save
Okay, now that we are able to link people with movies and movies with people, let's create a record in our database. Go to the The Godfather movie record that we created earlier. You'll be on the Details tab, but for that we have to add a record to the related list, Cast (which was added automatically by creating the relationship fields). So, click the Related tab and click New in the related Cast list. Fill in Michael Corleone as Role Name. Because we are creating a Cast record from the Movie record, the Movie lookup is already pre-populated with The Godfather. Now, click the lookup icon next to the Person field, select Al Pacino, and click Save (as illustrated in the following screenshot):
You have successfully added Al Pacino (the Person), to the Cast of The Godfather (our Movie) in the role of Michael Corleone! Now, do yourself a favor and navigate to our Al Pacino record and check out the Related tab there. You will find the same related Cast list and also the record for Michael Corleone played by Al Pacino in the movie The Godfather. I hope this example gives you a clear view on how a many-to-many relationship work.
Understanding the different relationship types and when and how to use them is a very important part of the Platform Developer I exam. So, make sure that you fully understand this. Feel free to create your own custom objects in your Developer Org and create multiple relationships to practice some more.
We will do the same in the next section, because, as you can see, we are not done yet! We'll be adding some extra relationships, but through Schema Builder instead of just through the Object Manager. Yep, I'm building up towards something here; no joke.