我有一些模型 - kanban_cards、kanban_checklists、kanban_checkitems。
kanban_cards 模型:
export default (sequelize, DataTypes) => {
return sequelize.define('kanban_card', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.STRING,
allowNull: false
},
label: {
type: DataTypes.STRING,
allowNull: true,
},
listId: {
type: DataTypes.UUID,
allowNull: false
},
...
})
}
看板 list :export default (sequelize, DataTypes) => {
return sequelize.define('kanban_checklist', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.STRING,
allowNull: false
},
cardId: {
type: DataTypes.UUID,
allowNull: false,
}
})
}
协会是:const models = {
KanbanCards: KanbanCards(sequelize, Sequelize.DataTypes),
KanbanChecklists: KanbanChecklists(sequelize, Sequelize.DataTypes),
...
}
...
models.KanbanCards.hasMany(models.KanbanChecklists, { as: 'checklists', foreignKey: 'cardId' })
models.KanbanChecklists.belongsTo(models.KanbanCards)
如果我使用 findAll
,它工作正常,但如果我尝试创建,它不起作用。它说。
关系“kanban_checklists”的列“kanbanCardId”不存在
我将使用
cardId
而不是 kanbanCardId
。我试图设置对
cardId
的引用,但它也不起作用。
最佳答案
如果您在 hasMany
中指定了一个显式外键列,您应该对另一部分执行相同的操作 - belongsTo
:
models.KanbanChecklists.belongsTo(models.KanbanCards, { foreignKey: 'cardId' })
否则 Sequelize 本身会生成一个外键名称,就像在您的情况下 kanbanCard
+ id
:The name of the foreign key in the join table (representing the target model) or an object representing the type definition for the other column (see Sequelize.define for syntax). When using an object, you can add a name property to set the name of the column. Defaults to the name of target + primary key of target
关于postgresql - hasMany ForeignKey 在 Sequelize 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67183303/