javascriptadonis.jslucid

AdonisJS 5 - preload model even if foreign key is null


I want to preload a model even if it have a null foreign key. I'll use the models from Adonis docs page to ilustrate: User and Profile.

const user = await User.query().preload("profile")

Simple as that!

But in my case, if a user have the key profile_id as null, it throws an exception, what means it only preload existing relationships (fair enough).

To make clear, I not want to preload just users with existing foreign keys, I need both existing user related models and users with no models to preload.

I have read and tested the examples from docs page, but it haven't enough explanation about this case (or I just didn't found it).

Any hints will be appreciated


Solution

  • Let me first answer your question, YES, you can preload Fk which are NULL.

    PS - you have not given any details apart from the query, so i am going to make some assumptions.

    Explanation-

    1. First you have to define relationship before using preload
    2. Relationsgip should be defined in the table which contains FK, in our case, its User table. e.g
    //User.ts or User.js
    import Profile from '/path/to/profile';
    
    ...
      @column()
      public profileId: number;
    
      @belongsTo(() => Profile)
      public profile: BelongsTo<typeof Profile>;
    ...
    

    As you can see, i have created a relationship in user table. i.e

      @belongsTo(() => Profile)
      public profile: BelongsTo<typeof Profile>;
    

    Once this is done, you can query user and preload profile.

    const user = await User.query().preload("profile")
    

    Now, if the user has profile, then it will be preloaded (join), and output will be something like this

    User {
     id: <random-number>,
     profileId: <random-number>,
     profile: {
      ...
     },
     ...
    }
    

    in case, profileId is null, then output will be something like this

    User {
     id: <random-number>,
     profileId: null,
     ...
    }
    

    ps - user variable is an array of User instance and i have given example of just 1 User instance.

    I hope this explanation has helped you.