我想在 Sequelize 中复制这个 MySQL 查询:
select u.email, a.serverId, ak.apikey from users u
join accounts a on u.id = a.userId
join apikeys ak on ak.userId = u.id
where u.state = "active" and ak.state = 1 and a.serverId = ak.serverId
这是我的翻译,除了我不知道如何实现的最终 and
子句 ( a.serverId = ak.serverId
):const activeKeys = await models.User.findAll({
attributes: ['email'],
raw: true,
where: {
state: "active"
},
include: [{
model: models.Account,
attributes: ['serverId']
},
{
model: models.Apikey,
attributes: ['apikey'],
where: {
state: 1
}
}]
})
我尝试了多种关联组合,这些是当前的组合:db.Account.belongsTo(db.User) // account has 1 user
db.User.hasMany(db.Account) // user has multiple accounts
db.User.hasMany(db.Apikey) // user has multiple apikeys
db.Apikey.belongsTo(db.User) // apikey has 1 user
db.Apikey.hasMany(db.Account) // apikey has many accounts
db.Account.hasOne(db.Apikey) // account has 1 apikey
唯一缺少的部分是 2 个包含模型之间的 and
子句。我怎样才能实现它?
最佳答案
在主 where
中尝试这样的事情:
where: Sequelize.and(
Sequelize.where(Sequelize.col("state"), "=", "active"),
Sequilize.where(Sequelize.col("Account.serverId"),"=", Sequelize.col("Apikey.serverId"))
)
关于mysql - Sequelize 3 个表与 2 个连接表之间的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67244401/