gpt4 book ai didi

node.js - Sequelize 复杂的 join 语句

转载 作者:太空宇宙 更新时间:2023-11-03 23:55:17 25 4
gpt4 key购买 nike

我最近从 C# 堆栈切换到全堆栈 javascript,并决定在我的项目中使用 Sequelize。我想编写一个查询,在其中获取用户以及相关的角色和租户对象。我使用官方文档作为指导,但不知何故我遗漏了一些东西。

我用作引用的文档: https://sequelize.org/master/manual/querying.html#relations---associations

数据库模型: enter image description here

检索用户的代码:

let user = await User.findOne({
where: { email },
[
include: {
model: Tenant,
where: { id: Sequelize.col('user.tenantId') }
},
include: {
model: Role,
where: { id: Sequelize.col('user.roleId') }
},

]
});

非常感谢任何帮助,干杯!

最佳答案

如果您在 sequlize 中定义了关联,则 include 中不需要条件,并且包含模型的方式可能存在语法问题,请检查以下查询:

User.findOne({
where: { email },
include: [
{
model: Tenant,
// where: { id: Sequelize.col('user.tenantId') } // <--- REMOVE
},
{
model: Role,
// where: { id: Sequelize.col('user.roleId') } // <--- REMOVE
}
]
});

关于node.js - Sequelize 复杂的 join 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57507868/

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