Playing Next Lesson In
seconds

Let's Learn AdonisJS 6 #5.0

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.

Created by
@tomgobich
Published

Join the Discussion 4 comments

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

    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
    1. Responding to noctisy
      @tomgobich

      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!
      2
      1. Responding to tomgobich
        @noctisy

        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
        1. Responding to noctisy
          @tomgobich

          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!! 😊

          2