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.

Published
Mar 22
Duration
6m 56s

Developer, dog lover, and burrito eater. Currently teaching AdonisJS, a fully featured NodeJS framework, and running Adocasts where I post new lessons weekly. Professionally, I work with JavaScript, .Net C#, and SQL Server.

Adocasts

Burlington, KY

Join The Discussion! (4 Comments)

Please sign in or sign up for free to join in on the dicussion.

  1. Commented 5 months ago

    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

    Please sign in or sign up for free to reply

    1. Commented 5 months ago

      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!

      0

      Please sign in or sign up for free to reply

      1. Commented 4 months ago

        Thanks, Tom.

        0

        Please sign in or sign up for free to reply

        1. Commented 4 months ago

          Anytime!!

          0

          Please sign in or sign up for free to reply