我有一个充满问题的问题表和一个包含我的用户列表的用户表。它们有多对多关系,其中包含带有外键uid(userid)和qid(questionid)的Junction表Question_User。
当我的用户回答问题时,我将其记录在Question_User中,以便我知道哪些用户已回答了哪个问题。它记录用户ID和他们回答的问题的ID。
我想查询特定用户未回答的每个问题。
module.exports = function(sequelize, DataTypes) {
var Question = sequelize.define("Question", {
qid: {
type: DataTypes.INTEGER,
primaryKey: true,
allowNull: false,
autoIncrement: true,
unique: true
},
question: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
option1: DataTypes.STRING,
option2: DataTypes.STRING,
option3: DataTypes.STRING,
option4: DataTypes.STRING,
option5: DataTypes.STRING
}, {
classMethods: {
associate: function(models) {
Question.belongsToMany( models.User, {
through: 'Question_User',
foreignKey: 'qid'
});
}
}
});
return Question;
};
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define("User", {
uid: {
type: DataTypes.INTEGER,
primaryKey: true,
allowNull: false,
autoIncrement: true,
unique: true
}
}, {
classMethods: {
associate: function(models) {
User.belongsToMany( models.Question, {
through: 'Question_User',
foreignKey: 'uid'
});
}
}
});
return User;
};
Models.Question.findAll({
include: [{
model: Models.User,
through: {
attributes: ['uid', 'qid']
}
}]
})
这会向Users数组添加已回答该问题的所有用户对查询返回的问题。