sequelizer中的一对多关系

时间:2018-10-12 10:19:23

标签: node.js sequelize.js

曾经查看过各种答案和git问题,但仍然无法正常工作。我有驱动程序模型和CarDrivers模型。驾驶员可以驾驶多辆汽车,所以我想建立一对多的关系。

Drivers Model是(models / drivers.js):

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

  };
  return Driver;
};

现在的CarDrivers(模型/cardrivers.js):

'use strict';


module.exports = (sequelize, DataTypes) => {
  const CarDriver = sequelize.define('CarDriver', {
    status: DataTypes.INTEGER,

  }, {});
  CarDriver.associate = function(models) {

    // associations can be defined here
    CarDriver.belongsTo(models.Driver, {
      onDelete: "CASCADE",
      foreignKey: 'id',
      as: 'car_driver'
    });
  };
  return CarDriver;
};

数据迁移没有错误,但在表CarDrivers中没有看到条目/相关列。任何人都可以帮助解决它。

1 个答案:

答案 0 :(得分:0)

您的代码存在问题,因为关联定义中的foreign_key不能为id,因为这将与id表的CarDriver冲突。如果将其更改为driver_id,您将在car_driver表中看到该列:

const Driver = sequelize.define('driver', {
  name: { type: Sequelize.STRING }
});

const CarDriver = sequelize.define('car_driver', {
  name: { type: Sequelize.STRING }
});

CarDriver.belongsTo(Driver, {
  onDelete: 'CASCADE',
  foreignKey: 'driver_id'
});

const driver = await Driver.create({
  name: 'first driver'
})

const carDriver = await CarDriver.create({
  name: 'first carDriver',
  driver_id: driver.id
})

两个注意事项:

  • foreignKey是可选的。如果将其保留为空白,则Sequelize将默认为驼峰式,例如driverId

  • 您的迁移文件必须说明CarDriver表上的外键:

    up: function(queryInterface, Sequelize) {
      return queryInterface.createTable('car_driver', {
        id: {},
        driver_id: {
          ..
        }
      });
    }