postgresql - hasMany ForeignKey 在 Sequelize 中不起作用

标签 postgresql foreign-keys sequelize.js

我有一些模型 - 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/

相关文章:

postgresql - 如何退出数据库恢复模式(目前锁定在只读模式)

postgresql - 如何让 psql 从 shell : $ psql -U admin -d mydb 在 ubuntu 中工作

postgresql - Mac OS X 10.11 - 将 Postgres 添加到 $PATH 失败

sql - 如何从其他表填充表的外键

mysql - SET FOREIGN_KEY_CHECKS = 0 在 Sequelize 迁移中不起作用

node.js - Sequelize : join query adding extra column which is not in model

database - 如何在postgresql中使用group by

sqlite - 在SQLite中实现/使用外键?

mysql - 如何给MySQL表添加外键?

javascript - 为什么 Sequelize 中会返回 Promise