In this video, @thetealpickle walks through creating relationships between models within a Swift-based API. The Swift API created in this video leverages the Vapor 3 framework. Models naturally interact with other models and in Vapor these model interactions are made possible by creating relationships. There are two types of relationships, one-to-many and many-to-many.
Code for this video can be found on @thetealpickle’s GitHub at 👉🏾 cheese-api-swift repository
Want to follow along? Get the starter code at the cheese-api-swift repository on the 👉🏾 vapor-relationships-start branch
One 👆🏾 to Many ✋🏾✋🏾✋🏾✋🏾✋🏾
A one-to-many relationship is referred to as a Parent/Child relationship. There is one parent model object which can map to many child objects. For example, a pet owner can have multiple pets, while each individual pet has one owner. In this scenario, the Owner model is the Parent model and the Pet model is the Child model.
Many ✋🏾✋🏾✋🏾✋🏾✋🏾 to Many ✋🏾✋🏾✋🏾✋🏾✋🏾
A many-to-many relationship is referred to as a Sibling relationship. Each sibling model object can map to many objects of the other sibling model, and vice versa. Continuing with the pet example, a pet can play with multiple toys and multiple toys can be played with by multiple pets. In this scenario, the Pet model and Toy model have a sibling relationship. Each model can map to multiple objects of the other model.
Relationships in Vapor
Vapor makes setting up relationships between models relatively straight forward. With Parent/Child relationships, the models are extended to have a computed property which returns the parent/children. With Sibling relationships, the models are linked using a Pivot model which stores the mapping between the sibling object ID’s. The pivot acts as the middle-women between the two models, the Sibling models are then extended to have a computed property based off of the pivot which manages and returns the siblings.
Working with Parent/Child relationships differ from Sibling relationships, as a safe guard must be added in the form of a foreign key constraint. Adding a foreign key constraint prevents the following (1) a child from being added to a nonexistent parent object, (2) the parent model table from being deleted prior to deleting the child model table, (3) the parent model object is not deleted until all children objects are deleted.
@thetealpickle on the internet. Namaste.
Brought to you by JESSICA JEAN JOSEPH © THETEALPICKLE