在Sequelize中创建关联

时间:2019-05-21 05:04:33

标签: node.js sequelize.js

我正在使用"sequelize": "^5.8.6",并且已经使用"sequelize-cli": "^5.4.0"创建了我的项目结构。我想创建关联,以便:

  

一家公司的评分很高

我创建了一个company模型,看起来像这样:

'use strict';
module.exports = (sequelize, DataTypes) => {
  const Company = sequelize.define('Company', {
    name: DataTypes.STRING,
    symbol: DataTypes.STRING,
  }, {});
  Company.associate = function(models) {
    Company.hasMany(models.Rating);
  };
  return Company;
};

我的Rating模型如下:

'use strict';
module.exports = (sequelize, DataTypes) => {
  const Rating = sequelize.define('Rating', {
    action: DataTypes.STRING,
  }, {});
  Rating.associate = function(models) {
    Rating.belongsTo(models.Company);
    // associations can be defined here
  };
  return Rating;
};

我的Company迁移如下所示:

'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Companies', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      name: {
        type: Sequelize.STRING
      },
      symbol: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Companies');
  }
};

我的Rating迁移如下所示:

'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Ratings', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      companyid: {
        type: Sequelize.INTEGER,
        references: {
          model: 'Company',
          key: 'id',
        },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL',
      },
      action: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Ratings');
  }
};

运行时,出现以下错误:

> npx sequelize-cli db:migrate

ERROR: Can't create table `test_db`.`ratings` (errno: 150 "Foreign key constraint is incorrectly formed")

有人建议我在做什么错吗?

感谢您的答复!

1 个答案:

答案 0 :(得分:0)

如果您还没有将其遗漏在代码中,则您的公司模型协会应显示为:

Company.associate = function(models) {
    Company.hasMany(models.Rating, {
        foreignKey: 'companyid',
        targetKey: 'id'
    });   
};

您的评分模型应为:

Rating.associate = function(models) {
     Rating.belongsTo(models.Company, {
     // associations can be defined here
         foreignKey: 'companyid',
         targetKey: 'id'
     });
};