如何使用Sequelize和mySqlselect外键列的名称?

我正在使用sequelize在我的节点应用程序中为mySql数据库模式build模。 我的模型摘录如下所示:我有一个公司表和一个部门表。 一个公司可以有多个部门,一个部门只属于一个公司。 我build模如下:

公司表:

module.exports = function(sequelize, DataTypes){ return Company = sequelize.define('Company', { companyId: { type: DataTypes.INTEGER, primaryKey: true, allowNull: false, autoIncrement: true, unique: true }, name: { type: DataTypes.STRING, allowNull: false } })} 

部门表:

 var Company = require('./company'); module.exports = function(sequelize,DataTypes) { return Department = sequelize.define('Department', { departmentId: { type: DataTypes.INTEGER, primaryKey: true, allowNull: false, autoIncrement: true, unique: true }, name: { type: DataTypes.STRING, allowNull: false }, companyId: { type: DataTypes.INTEGER, references: 'Companies', referencesKey: 'companyId', onDelete: 'cascade' } });} 

要实际存储这个架构在数据库中我使用下面的代码:

 var db = require('../models/index'); db["Company"].hasMany(db["Department"], {as: 'departments'}); db["Department"].belongsTo(db["Company"], {foreignKey: 'companyId', foreignKeyConstraint: true}); models.sequelize.sync().complete(function(err){ //irrelevant for the problem }); 

问题是这段代码在部门表中创build了2个外键。 一个在“companyId”字段(正如所期望的),另一个字段“CompanyCompanyId”是一个自动生成的字段。

我怎样才能确保只有我定义的外键('companyId')被使用和创build?

我设法解决这个问题:

而不是只在belongsTo语句中使用“foreignKey”选项,它也应该用在“hasMany”语句中。

在原始问题中发布的两个模型保持不变。 我唯一需要改变的是foreignKey选项的位置:

 var db = require('../models/index'); db["Company"].hasMany(db["Department"], {as: 'departments'}); db["Department"].belongsTo(db["Company"], {foreignKey: 'companyId', foreignKeyConstraint: true}); 

变成:

 var db = require('../models/index'); db["Company"].hasMany(db["Department"], { foreignKey: 'companyId'}); db["Department"].belongsTo(db["Company"], {foreignKey: 'companyId'}); 

Sequelize会为您创buildForeignKey字段。 因此,如果您使用的是belongsTo ,则无需在Department模型中定义字段belongsTo

在当前场景中,它将创build两个在模型中定义的外键,另一个通过belongsTo创build,当它尝试再次创buildforeignKey时,它会发现该字段已经存在,因此会创build另一个字段。

在4.4.0版本中,belongsTo函数有一个targetKey选项。

 const User = this.sequelize.define('user', {/* attributes */}) const Company = this.sequelize.define('company', {/* attributes */}); User.belongsTo(Company, {foreignKey: 'fk_companyname', targetKey: 'name'}); // Adds fk_companyname to User 

有关http://docs.sequelizejs.com/manual/tutorial/associations.html#target-keys的更多信息