Playing Next Lesson In
seconds

Let's Learn AdonisJS 6 #5.4

Defining One to Many Relationships with Lucid Models

In This Lesson

We'll learn how to define one-to-many and many-to-one relationships using Lucid Models. We'll also learn how we can specify the columns that should be used for a relationship, allowing us to use one model for multiple relationships.

Created by
@tomgobich
Published

Join the Discussion 4 comments

Create a free account to join in on the discussion
  1. @cbernard

    Hi Tom, is there any way to do a polymorphic relationship? Or how would you accomplish having a model (e.g. Comments) that could belong to more than one model type (e.g. Movies and Cinests)?

    1
    1. Responding to cbernard
      @tomgobich

      Hey cbernard! Currently, there isn't a way to do polymorphic relationships with Lucid support. There are a couple of solutions you could use, maybe others as well.

      1. Define a relationship column per relationship. If you only have a few tables needing the polymorphic relationship, you could just define an id column for each individual relationship, for example on comments you could have a nullable movie_id and a nullable cineast_id column.

        This is the approach I use for comments here on the Adocasts site.

      2. You could create a pivot table per relationship, for example, a movie_comments and cineast_comments. In this case, don't think of it as a many-to-many, but rather a has many with an additional has one step. movie → has many comments (movie_comments) → has one comment (comments).

      Hope this helps!

      1
      1. Responding to tomgobich
        @cbernard

        Thanks, Tom.

        0
        1. Responding to cbernard
          @tomgobich

          Anytime!!

          0