4. Consider this Sequelize association code with an error:
Order.hasMany(Item);
Item.belongsTo(Order);
// Later in code
const order = await Order.findByPk(1);
const items = await order.getItem();
What is the error and how to fix it?
medium
A. Order should use belongsTo, not hasMany.
B. belongsTo should be called on Order, not Item.
C. Method getItem() is incorrect; should be getItems() because hasMany creates plural getter.
D. findByPk is not a valid Sequelize method.
Solution
Step 1: Identify the association methods
Order hasMany Item means Sequelize creates getItems() method on Order instances, not getItem().
Step 2: Fix the method call
Change order.getItem() to order.getItems() to correctly fetch related items.
Final Answer:
Method getItem() is incorrect; should be getItems() because hasMany creates plural getter. -> Option C
Quick Check:
hasMany creates plural get method [OK]
Hint: hasMany creates plural get method, use getItems() [OK]
Common Mistakes:
Using singular get method for hasMany
Confusing belongsTo direction
Thinking findByPk is invalid
5. You have two models: User and Profile. Each User has one Profile, and each Profile belongs to one User. Which Sequelize associations correctly represent this, and what methods will be available on User instances?
hard
A. User.belongsTo(Profile); Profile.hasOne(User); with user.getProfile() method.
B. User.hasMany(Profile); Profile.belongsTo(User); with user.getProfiles() method.
C. Profile.hasOne(User); User.belongsTo(Profile); with user.getProfile() method.
D. User.hasOne(Profile); Profile.belongsTo(User); with user.getProfile() method.
Solution
Step 1: Identify one-to-one relationship
Each User has one Profile means hasOne is used, not hasMany.
Step 2: Set belongsTo on Profile
Profile belongs to User, so Profile.belongsTo(User); is correct.
Step 3: Check available methods
User instances get getProfile() method for the single related Profile.
Final Answer:
User.hasOne(Profile); Profile.belongsTo(User); with user.getProfile() method. -> Option D
Quick Check:
One-to-one uses hasOne + belongsTo [OK]
Hint: One-to-one uses hasOne + belongsTo with singular get method [OK]