There are 3 types of relationship parameters that you can use for your database collections. One-to-many, many-to-one, and many-to-many. Let’s explore how each of them works.
One-to-many relationships are the most common type of relationship. In a one-to-many relationship, a record in one table can be linked to multiple records in another table.
In a many-to-one relationship, multiple records in one table can be linked to a single record in another table.
In a many-to-many relationship, multiple records in one table can be linked to multiple records in another table.
Creating a one-to-many automatically creates the many-to-one relationship on the 2nd collection.
So if you create a one-to-many relationship in the user collection between Posts and Users where a user can have many posts and posts belong to 1 user, it will automatically create the relationship parameter in the posts collection of many-to-one where posts belong to 1 user and a user can have many posts.
Here are some examples of one-to-many relationships:
- A customer can have multiple orders.
- An order can have multiple items.
- A user can have multiple social media posts.
- A company can have multiple employees.
- A course can have many lessons.
Here are some examples of many-to-one relationships:
- Comments belong to a single social media post.
- Employees can be tied to one company.
- Companies can have a single owner.
- Restaurants can be put in a single category.
- Lessons belong to one course.
Here are some examples of many-to-many relationships:
- Users can block other users.
- Users can have multiple interests.
- Social media posts can have many “liked by” users.
- Tasks can be assigned to multiple users.
- Restaurants can be in many cities.
Let’s say you want to create a “support ticket” app where you provide customer support to your customers.
You would have a “Tickets” collection.
This collection would contain the following parameters:
Ticket ID # (Number)
Creating User (one-to-many, a ticket belongs to 1 user, users can create many tickets)
Ticket Replies (many-to-one, tickets can have many replies, Replies belong to 1 ticket)
Ticket Status (one-to-many, tickets can have 1 status, Statuses can have multiple tickets)
Ticket Category (one-to-many, tickets can have 1 category, Categories can have multiple tickets)
Ticket Images (many-to-one, tickets can have many images, Images belong to 1 ticket)