Defining One to One Relationships Within Lucid Models

In this lesson, we'll learn how to define one-to-one relationships within our Lucid Models. We'll learn about the belongs to and has one decorators, their options, and types that make this possible.

Published
Mar 18
Duration
5m 49s

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 25 days ago

    Hello Tom,

    I'm used to working with Doctrine (ex Symfony users!) as an ORM, but I must admit that Lucid works a bit differently and I'm a bit confused about the need to keep both the userId declaration and the user relationship. Can't we just use the user relationship?

    1

    Please sign in or sign up for free to reply

    1. Commented 24 days ago

      Hi noctisy!

      With Lucid, relationships work with and directly read off of the model. So, if you omit the userId but define the relationship, you'll end up getting an exception.

      Though I don't know the core team's exact reasoning, I'd imagine it is so the relationship can make use of the column decorator's mutations to build out the relationship columns. It could also be for compatibility with hooks as well.

      For example, you might want a different naming convention in the model than in the table.

      export default class Profile {
        @column({ isPrimary: true })
        declare id: number
      
        @column({
          columnName: 'profile_user_id', // column name in db
          serializeAs: null, // omit from serialization (maybe it is confidential)
        })
        declare userId: number
      
        @belongsTo(() => User)
        declare user: BelongsTo<Typeof User>
      }
      Copied!
      1

      Please sign in or sign up for free to reply

      1. Commented 24 days ago

        Thank you a lot for the clarification Tom! It was a bit confusing at first but after a second watch of the whole relationship part (5.0 → 5.13), it's more clear. Thanks for the resources too!

        1

        Please sign in or sign up for free to reply

        1. Commented 24 days ago

          Awesome & anytime! I'm happy to hear things are clicking for you. If there is anything you feel would help make things clearer for the first go around, I'm all ears!! 😊

          1

          Please sign in or sign up for free to reply