mysql - Sequelize 3 个表与 2 个连接表之间的位置

标签 mysql node.js sequelize.js

我想在 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/

相关文章:

node.js - 有没有办法让一个人在子域中通过 firebase 进行身份验证

javascript - Sequelize findOne错误: TypeError indexOf undefined

php - 在 PHP/MySQL 中使用数组

php - 使用 MySQL 表数据填充 HTML 表

node.js - 在我的 Nodejs API 中使用 Mongoose 发布到 MongoDB Atlas 时无法正常工作

javascript - 数据库表中唯一的随机字符串

javascript - 如何反序列化包含的模型属性?

node.js - 为什么 Sequelize 将我的日期时间更改为 T00 :00:00Z?

mysql - 我已导出 Mysql 数据库,但在导入新版本时遇到语法问题

php - 当单选按钮的名称是变量时,如何从单选按钮获取数据?