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 ?