Does defining relationships in models using sequilizejs partially or completely remove the need for using include parameter?

Viewed 22

What is the advantage of defining relationships in sequilizejs on a given modal , is it just for the purpose of more succinct queries ? I do see an example such as (Found HERE) :-

User.hasMany(Picture)
User.belongsTo(Picture, { as: 'ProfilePicture', constraints: false })

user.getPictures() // gets you all pictures
user.getProfilePicture() // gets you only the profile picture

User.findAll({
  where: ...,
  include: [
    { model: Picture }, // load all pictures
    { model: Picture, as: 'ProfilePicture' }, // load the profile picture. Notice that the spelling must be the exact same as the one in the association
  ]
})

Does having a relationship defined avaoid the usage of too many queries with the include param ? I.E. does the below :-

user.getPictures() // gets you all pictures
user.getProfilePicture() // gets you only the profile picture

Do away with the more verbose :-

User.findAll({
      where: ...,
      include: [
        { model: Picture }, // load all pictures
        { model: Picture, as: 'ProfilePicture' }, // load the profile picture. Notice that the spelling must be the exact same as the one in the association
      ]
    })

I am using sequilizejs in an already existing project so the models were not created by me and hence an trying to understand the advantage of having relationships such as belongsTo and hasOne being defined in a model. Would appreciate any insight into the same.

P.S. I do see a more detailed documentation HERE

Also , as a secondary question what are the other advantages of using relationships in a db ?

1 Answers

Defining the relationships is actually required to be able to use include in the queries.

By using include, Sequelize will create a JOIN query, so you can get data from multiple collections which are linked by relationships without the need of a second query.

When using belongsTo, hasOne, hasMany etc. these methods are creating aditional columns in the table to create the relationships between the tables.

Related