【问题标题】:Sequelize doesn't create a foreign key column on a populated tableSequelize 不会在填充的表上创建外键列
【发布时间】:2021-02-22 10:47:01
【问题描述】:

这是我常用的示例数据库: https://www.mysqltutorial.org/mysql-sample-database.aspx/

我需要使用 squelize 在支付表中创建一个 customer_id 外键:

  payments.belongsTo(customers, {
        foreignKey: 'customer_id',
    });

不幸的是,foreignKey 列不是由 sequelize 自动创建的,但是,如果我使用此命令:

sequelize.sync({ force: true })

列已创建,但我的整个数据库内容已清除!

  1. 保留我的实际数据的解决方案是什么?
  2. 是否必须手动创建每个外部列?
  3. 如果是,具体语法是什么?

非常感谢!

P.S :表格中填充了示例数据。我不想清除这些数据。 P.S:我使用https://github.com/sequelize/sequelize-auto从现有数据库生成数据模型。

【问题讨论】:

  • 这能回答你的问题吗? Foreign keys with Sequelize are not created
  • 不,我想知道 Sequelize 是否可以在填充的表上创建外键,谢谢,我以前看过这篇文章。
  • 我需要 100% 确定 Sequelize 是否可以在填充的表上创建外键
  • 我对 Sequelize.JS 不熟悉。希望您能得到答复。

标签: mysql node.js sequelize.js


【解决方案1】:

在您的模型付款中添加foreignKey 以及下面的其他列,您可以在您提供的存储库链接的 git 自述文件中看到此示例

示例 = https://github.com/sequelize/sequelize-auto#typescript

payments.belongsTo(customers, {
  foreignKey: 'customer_id',
  targetKey: 'id'
});

customer_id: {
  type: DataTypes.INTEGER(),
    allowNull: false,
      references: {
    model: 'customers',
      key: 'id'
  }
}

【讨论】:

  • 非常感谢!我今晚会试试这个,请注意,为了更简单,我更改了一些初始消息(customerNumber_id 变为 customer_id)
猜你喜欢
  • 2018-01-05
  • 1970-01-01
  • 2014-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-10
  • 2021-12-21
  • 1970-01-01
相关资源
最近更新 更多