我正在尝试定义模型Survey
和Question
之间的M:N关系。关系的名称是SurveyHasQuestions
,它也有一个定义(进一步了解它如何在关联定义中使用):
var SurveyHasQuestions = sequelize.define('survey_has_questions', {
shq_id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
}
}, {
tableName: 'survey_has_questions'
});
Survey
和Question
的表在DB中正确生成(顺便说一句是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)
但是通过警告提醒抱怨: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
。
现在我知道如果在fix
的定义中我移除了我自己的主键SurveyHasQuestions
并且将fkeys的组合用作pkey,我可以shq_id
这种情况。但即使从技术上讲,串口pkey可能不提供关系中的任何东西(它甚至可能是开销),但据我所知,定义它并不违法。
其他人遇到过这种行为吗?有没有办法解决它,即仅使用belongsToMany()
定义关联并仍然获得survey_has_questions
的正确表格结构?
答案 0 :(得分:3)