gpt4 book ai didi

javascript - Sequelize 多对多关系表获取不需要的额外列

转载 作者:搜寻专家 更新时间:2023-10-31 23:48:08 24 4
gpt4 key购买 nike

我正在尝试定义模型 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.请改用 belongsToMany

所以为了正确地做事,我试过只使用 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 并让组合的 fkey 作为 pkey。但即使从技术上讲串行 pkey 可能不会在关系中提供任何东西(它甚至可能是开销),但据我所知,定义一个 pkey 并不违法。

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

最佳答案

关于javascript - Sequelize 多对多关系表获取不需要的额外列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28578745/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com