0
0
Expressframework~10 mins

Associations (hasMany, belongsTo) in Express - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Associations (hasMany, belongsTo)
Define Models
Set hasMany on Parent
Set belongsTo on Child
Create Parent Instance
Create Child Instance(s)
Link Child to Parent
Query Parent with Children
Query Child with Parent
Use Associations in Code
This flow shows how to define two models with hasMany and belongsTo associations, create instances, link them, and query related data.
Execution Sample
Express
const User = sequelize.define('User', { name: DataTypes.STRING });
const Post = sequelize.define('Post', { title: DataTypes.STRING });
User.hasMany(Post);
Post.belongsTo(User);
Defines User and Post models, then sets User hasMany Posts and Post belongsTo User associations.
Execution Table
StepActionModel StateAssociation SetResult
1Define User modelUser model createdNoneUser ready
2Define Post modelUser, Post models createdNonePost ready
3User.hasMany(Post)User, Post modelsUser hasMany PostForeign key added to Post
4Post.belongsTo(User)User, Post modelsPost belongsTo UserForeign key confirmed on Post
5Create User instanceUser instance createdAssociations intactUser saved
6Create Post instanceUser instance, Post instance createdAssociations intactPost saved
7Link Post to UserInstances linkedAssociations usedPost.UserId set
8Query User with PostsUser with Posts loadedAssociations usedUser.posts array populated
9Query Post with UserPost with User loadedAssociations usedPost.User object populated
10Use associations in codeData accessible via associationsAssociations usedRelated data available
💡 All steps complete, associations set and used successfully
Variable Tracker
VariableStartAfter Step 5After Step 6After Step 7After Step 8After Step 9Final
UserModelDefinedInstance createdInstance createdInstance createdInstance with postsInstance with postsInstance with posts
PostModelDefinedNot createdInstance createdInstance linkedInstance linkedInstance with userInstance with user
UserInstanceNoneCreatedCreatedCreatedLoaded with postsLoaded with postsLoaded with posts
PostInstanceNoneNoneCreatedLinked to userLinked to userLoaded with userLoaded with user
Post.UserIdUndefinedUndefinedUndefinedSet to User idSet to User idSet to User idSet to User id
Key Moments - 3 Insights
Why do we call hasMany on the parent model and belongsTo on the child model?
hasMany sets up the parent to hold multiple children, while belongsTo sets the child to reference one parent. See execution_table steps 3 and 4 where associations are set.
How does the foreign key get added to the child model?
When hasMany and belongsTo are set, the child model automatically gets a foreign key to link to the parent. This is shown in execution_table step 3 and 4.
How do we access the related data after querying?
After querying with associations, related data is available as properties like user.posts or post.user, as shown in steps 8 and 9.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 7. What happens to Post.userId?
AIt is set to the User instance's id
BIt remains undefined
CIt is deleted
DIt is set to null
💡 Hint
Check the 'Result' column at step 7 in execution_table
At which step do we first create an instance of the Post model?
AStep 5
BStep 6
CStep 3
DStep 8
💡 Hint
Look at the 'Action' column in execution_table for instance creation
If we remove Post.belongsTo(User), what would happen to the foreign key on Post?
AIt would not be added automatically
BIt would be added to User instead
CIt would still be added by hasMany
DIt would cause an error
💡 Hint
Refer to execution_table steps 3 and 4 about foreign key addition
Concept Snapshot
Associations (hasMany, belongsTo) in Express Sequelize:
- Use hasMany on parent to link multiple children
- Use belongsTo on child to link single parent
- belongsTo adds foreign key to child model
- Create instances, then link child.UserId to parent.id
- Query with include to get related data
- Access related data via parent.children or child.parent
Full Transcript
This visual execution trace shows how to set up associations between two models in Express using Sequelize. First, we define two models: User and Post. Then, we set User.hasMany(Post) to indicate one user can have many posts, and Post.belongsTo(User) to indicate each post belongs to one user. These associations add a foreign key to the Post model linking it to User. We create instances of User and Post, then link the post to the user by setting post.UserId. Queries with associations include related data, accessible as user.posts or post.user. This step-by-step trace helps beginners see how associations work in practice.