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

Sequelize+MySQL:查询问题并关联指定用户回答(无回答仍保留问题)

解决方法

核心逻辑是使用左外连接保留所有状态为1的Question,同时将user_id的过滤条件放在关联的on子句中,而非主查询的where条件里。

具体代码实现

假设基础模型定义如下:

// Question 模型
const Question = sequelize.define('Question', {
  id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
  title: DataTypes.STRING,
  status: DataTypes.INTEGER // 1为有效状态
});

// Question_Answers 模型
const QuestionAnswer = sequelize.define('Question_Answers', {
  question_id: DataTypes.INTEGER,
  answer: DataTypes.TEXT,
  user_id: DataTypes.INTEGER
});

// 建立一对多关联
Question.hasMany(QuestionAnswer, {
  foreignKey: 'question_id',
  as: 'answers' // 关联别名
});

查询代码示例:

const targetUserId = 123; // 指定要匹配的用户ID

const questions = await Question.findAll({
  where: {
    status: 1 // 仅查询状态为1的问题
  },
  include: [
    {
      model: QuestionAnswer,
      as: 'answers',
      required: false, // 关键:设为false启用左外连接,保留主表所有符合条件的记录
      where: {
        user_id: targetUserId // 将用户ID过滤放在关联条件中
      }
    }
  ]
});

关键说明

  • required: false:Sequelize中默认required: true是内连接,会过滤掉无关联回答的问题;设为false后启用左外连接,确保所有状态为1的问题都会被返回。
  • 过滤条件位置:把user_id的判断放在include的where里,只会筛选该用户的关联回答,不会影响主表问题的返回;如果放在主查询where中,会过滤掉无对应回答的问题,不符合需求。
  • 无回答时表现:配置正确的情况下,无对应回答的问题的answers字段会自动返回空数组。

内容的提问来源于stack exchange,提问作者Ankit Shah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 19:04:07