繁体   English   中英

无法使用 Sequelize 添加外键约束

[英]Cannot add foreign key constraint using Sequelize

尝试使用 sequelize 创建待办事项列表,但我总是遇到此错误:“无法使用 Sequelize 添加外键约束” 即使在 StackOverflow 中寻找一些线索,somone 可以提供帮助吗?

待办事项迁移

module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable('Todos', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER,
      },
      description: {
        type: Sequelize.STRING,
        allowNull: false,
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
      status_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: 'Statuses',
          key: 'id',
        },
      },
    });
  },
  async down(queryInterface) {
    await queryInterface.dropTable('Todos');
  },
};

状态迁移

module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable('Statuses', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER,
      },
      name: {
        type: Sequelize.STRING,
        allowNull: false,
      },
    });
  },
  async down(queryInterface) {
    await queryInterface.dropTable('Statuses');
  },
};

Relationship in models

// Status model
  Status.associate = (models) => {
    Status.belongsTo(models.Todo, { foreignKey: 'status_id', as: 'todo' });
  };

// Todo model
  Todo.associate = (models) => {
    Todo.hasMany(models.Status, { foreignKey: 'status_id', as: 'statuses' });
  };

如果有人有任何想法,我真的很感激! 谢谢

当“Todos”表有“status_id”时,

它必须“属于”“状态”表。

或者您应该将“todo_id”保存在“状态”表中。

  // Status model
  Status.associate = (models) => {
    Status.hasMany(models.Todo, { foreignKey: 'status_id', as: 'todos' });
  };

  // Todo model
  Todo.associate = (models) => {
    Todo.belongsTo(models.Status, { foreignKey: 'status_id', as: 'status' });
  };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM