【问题标题】:Sequelize many-to-many relationship table gets unneeded extra columnSequelize 多对多关系表获得不需要的额外列
【发布时间】:2015-04-19 04:00:07
【问题描述】:

我正在尝试定义模型 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 表:

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 生成不正确的表:

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 获得正确的表结构?

【问题讨论】:

    标签: javascript node.js entity-relationship sequelize.js


    【解决方案1】:
    猜你喜欢
    • 2010-11-25
    • 2023-02-02
    • 2011-03-23
    • 1970-01-01
    • 2020-10-31
    • 1970-01-01
    • 1970-01-01
    • 2011-07-29
    • 1970-01-01
    相关资源
    最近更新 更多