DongDong
DongDong

Reputation: 57

Sequelize, How to use findAll when a table has belongsTo and belongsToMany relations with same table

I used Sequelize to handle database.

I have three tables like below User Item Like

User has 1:N relationship with Item. That means one user can create several items on my program.
Also, user can handle like(favorite) states when click heart icon. So I made N:M relation between User and Item table. It creates Like table that has userIdx and itemIdx for its property.
Belows are relations.

User

db.User.hasMany(db.Item, { foreignKey: 'userIdx', sourceKey: 'userIdx' });
db.User.belongsToMany(db.Item, { through: 'Like', foreignKey: 'userIdx' });

Item

db.Item.belongsTo(db.User, { foreignKey: 'userIdx', targetKey: 'userIdx' });
db.Item.belongsToMany(db.User, { through: 'Like', foreignKey: 'itemIdx' });

Like

db.Like.belongsTo(db.User, { foreignKey: 'userIdx' });
db.Like.belongsTo(db.Item, { foreignKey: 'itemIdx' });

I want to get two information with join(include)

  1. a user who create the item
  2. several users who like the item

I used below code

const result = await Item.findAll({
    include: [
        {
            model: User
        }
    ],  
})

But It shows only userIdx who create item. I also want to get all users who likes the item.

item: {
    ...
    userIdx: (show by user-item 1:n relationship),
    likeStateUsers: [(show by user-item n:m relationship)]
    ...
}

Thanks for reading

Upvotes: 0

Views: 456

Answers (1)

Ejaz khan
Ejaz khan

Reputation: 2095

first of all update item model.
db.Item.belongsTo(db.User, {as:'createdbyUser', foreignKey: 'userIdx', targetKey: 'userIdx' });
//add this line to item model
db.Item.hasMany(db.Like, {as:'itemlikes', foreignKey: 'userIdx', sourceKey: 'userIdx' });

then write this code 
const result = await Item.findAll({
    include: [
        {
            model: User ,as:'createdbyUser' , 
           },
{model:Like,as:'itemlikes', 
include:[{
model:User
}]
}],  
})

Upvotes: 1

Related Questions