Sequelize 多对多关系 table 获取不需要的额外列

Sequelize many-to-many relationship table gets unneeded extra column

我正在尝试定义模型 SurveyQuestion 之间的 M:N 关系。关系的名称是 SurveyHasQuestions,它也有一个定义(进一步了解它在关联定义中的使用方式):

var SurveyHasQuestions = sequelize.define('survey_has_questions', {
    shq_id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    }
}, {
    tableName: 'survey_has_questions'
});

SurveyQuestion 的表在数据库中正确生成(顺便说一句,它是 Postgres):

survey_id: integer (pkey)
survey_url: string
date: timestamp

question_id: integer (pkey)
question_text: string

现在,以下协会:

Survey.hasMany(SurveyQuestion, {through: SurveyHasQuestions, foreignKey: 'survey_id'});
SurveyQuestion.hasMany(Survey, {through: SurveyHasQuestions, foreignKey: 'question_id'});
SurveyHasQuestions.belongsTo(Survey, {foreignKey: 'survey_id'});
SurveyHasQuestions.belongsTo(SurveyQuestion, {foreignKey: 'question_id'});

工作正常,即它们为具有所需结构的 M:N 关系生成 survey_has_questions table:

shq_id: integer (pkey)
question_id: integer (fkey references survey_question.question_id)
survey_id: integer (fkey references survey.survey_id)

但 sequelize 抱怨警告:Using 2 x hasMany to represent N:M relations has been deprecated. Please use belongsToMany instead

所以为了正确地做事,我试过只使用 belongsToMany()。但是这些协会:

SurveyQuestion.belongsToMany(Survey, {
    through: SurveyHasQuestions,
    foreignKey: 'question_id'
});
Survey.belongsToMany(SurveyQuestion, {
    through: SurveyHasQuestions,
    foreignKey: 'survey_id'
});

survey_has_questions 生成不正确的 table:

shq_id: integer (pkey)
question_id: integer (fkey references survey_question.question_id)
survey_survey_id: integer (fkey references survey.survey_id) <---??? UNWANTED
survey_id: integer (fkey references survey.survey_id)

问题是额外的列 survey_survey_id 完全没有任何作用,因为它是另一列 survey_id 的副本。

有趣的是,如果我颠倒 .belongsToMany() 语句的顺序,我会得到一个额外的字段 survey_question_question_id 来代替 survey_survey_id.

现在我知道如果在 SurveyHasQuestions 的定义中删除我自己的主键 shq_id 并让 fkeys 的组合作为 pkey,我可以 fix 这种情况.但是,即使从技术上讲,序列 pkey 可能不会在关系中提供任何东西(它甚至可能是一种开销),但据我所知,定义一个 pkey 并不违法。

还有其他人遇到过这种行为吗?有没有办法解决它,即仅使用 belongsToMany() 定义关联,并且仍然为 survey_has_questions 获得正确的 table 结构?

这是一个错误:https://github.com/sequelize/sequelize/issues/2991

此问题已在 v2.0.3 的最新版本中修复:https://github.com/v12/sequelize/commit/73f875a935db911621ece8c2d86685c22c79a90e

在此处获取 v2.0.3:https://github.com/sequelize/sequelize/releases/tag/v2.0.3