gpt4 book ai didi

sequelize.js - 在 Sequelize 多对多查询中使用 'where'

转载 作者:行者123 更新时间:2023-12-03 22:35:19 25 4
gpt4 key购买 nike

刚开始使用 sequelize,您如何使用“where”来指定表上的条件?我有这样定义的属地关系:

db.users.belongsToMany(db.groups, {through: "users_groups", foreignKey:"user_id"});
db.groups.belongsToMany(db.users, {through: "users_groups",foreignKey:"group_id"});

1)我希望能够查看用户是否在给定用户 ID 的组中

2)我想检索给定用户ID的用户参加的所有组和组信息

在这些情况下,我应该把“哪里”放在哪里?

我试过了
Group.findOne({
through: {where:{id:req.body.group_id}},
include: [{
model: User,
through:{
where:{id:req.body.user_id}
}
}]
}).then(data=>{
res.send(data);
})

最佳答案

through 属性需要一个连接模型或别名,你给它一个 where caluse。

const { group_id: groupId, user_id: userId } = req.body;

Group.findOne({
where: { id: groupId },
include: [{
model: User,
through: 'users_groups',
where: { id: userId },
}]
}).then(data=>{
res.send(data);
})

欲了解更多信息 read here

关于sequelize.js - 在 Sequelize 多对多查询中使用 'where',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61673674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com