You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Sequelize中设置复杂关联查询条件?

将目标SQL转换为Sequelize查询

没问题,我帮你把这段SQL转换成Sequelize的实现。先梳理下原SQL的逻辑:它要找出和uid为11的用户存在匹配关系的记录,关联用户表和用户资料表,返回指定的字段集合。

假设你已经定义好了Matches、Users、ProfileUsers这三个Sequelize模型,下面是对应的查询代码:

const { Op, where, col } = require('sequelize');

const matchedRecords = await Matches.findAll({
  // 指定要从matches表返回的字段
  attributes: ['uid_prop', 'uid_player', 'porcentaje'],
  include: [
    {
      model: Users,
      // 指定users表返回的字段
      attributes: ['uid'],
      required: true, // 对应SQL中的内连接JOIN
      where: {
        [Op.or]: [
          // 第一种匹配场景:当前用户是player(uid=11),关联prop对应的用户
          {
            [Op.and]: [
              where(col('matches.uid_prop'), '=', col('users.uid')),
              { '$matches.uid_player$': 11 }
            ]
          },
          // 第二种匹配场景:当前用户是prop(uid=11),关联player对应的用户
          {
            [Op.and]: [
              where(col('matches.uid_player'), '=', col('users.uid')),
              { '$matches.uid_prop$': 11 }
            ]
          }
        ]
      },
      include: [
        {
          model: ProfileUsers,
          // 指定profile_users表返回的字段
          attributes: ['name', 'profile', 'birthday', 'location'],
          required: true, // 内连接JOIN,对应SQL中的JOIN profile_users USING(uid)
        }
      ]
    }
  ],
  // 原SQL末尾的WHERE过滤条件
  where: {
    uid_player: 11
  },
  // 如果需要原始JSON数据而非Sequelize模型实例,可以设置raw: true
  raw: false
});

关键细节说明:

  • 使用col()来跨表引用字段,避免字段名冲突,这对应SQL中直接写表名.字段名的写法
  • 通过Op.or和Op.and组合条件,完全还原原SQL中的逻辑判断
  • required: true确保使用内连接(INNER JOIN),和原SQL的JOIN行为一致
  • 关联ProfileUsers时,只要你在模型中已经基于uid字段设置了关联(比如Users.hasOne(ProfileUsers, { foreignKey: 'uid' })),Sequelize会自动处理USING(uid)的关联逻辑

如果还没设置模型关联,这里补充一下基础关联代码:

// 在Users模型中定义与ProfileUsers的一对一关联
Users.hasOne(ProfileUsers, { 
  foreignKey: 'uid', 
  sourceKey: 'uid',
  as: 'profile' // 可以设置别名,方便后续引用
});
ProfileUsers.belongsTo(Users, { 
  foreignKey: 'uid', 
  targetKey: 'uid'
});

内容的提问来源于stack exchange,提问作者Juan Astorelli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:07:40