在多个文件中join一对多的关联

我正在研究一个到多个关联的续集。 大多数教程和文档都显示了两个模型在同一个文件中定义的示例。 我目前有两个文件,第一个city.js:

const Promise = require('bluebird'); var Country = require('./country'); var City = sequelize.define("City", { id: { type: DataTypes.INTEGER, field: 'id', primaryKey: true, autoIncrement: true },... }, { freezeTableName: true, timestamps: false }); City.belongsTo(Country, {foreignKey : 'countryId', as: 'Country'}); Promise.promisifyAll(City); module.exports = City; 

和第二个文件country.js:

 const Promise = require('bluebird'); var City = require('./city'); var Country = sequelize.define("Country", { id: { type: DataTypes.INTEGER, field: 'id', primaryKey: true, autoIncrement: true }, ... }, { freezeTableName: true, timestamps: false, paranoid: false }); Country.hasMany(City, {foreignKey : 'countryId', as: 'Cities'}); Promise.promisifyAll(Country); module.exports = Country; 

当我导入两个模块并尝试实例化对象时:

 var City = require('../model/external/city'); var CountryRepository = require('../repository/external/countryRepository'); CountryRepository.findById(1).then(function(country) { var city = City.build(); city.name = 'Paris'; city.setCountry(country); console.log('OK'); }); 

我得到以下错误:

抛出新的错误(this.name +'。'+ Utils.lowercaseFirst(Type.toString())+'调用一些不是Sequelize.Model的实例)

模型在从模型中导出之前是否被模糊化了,还是我错过了一些东西?

我不确定你的代码到底是什么问题,需要运行它才能确定。

但是正如你正在寻找一个例子,看看这个来自Sequelize Github的例子。

它在不同的文件中声明模型并将它们关联到index.js

稍后,您可以使用简单的model属性模型引用您的其他模型。国家/地区:

 City.belongsTo(model.Country, {foreignKey : 'countryId', as: 'Country'}); 

比如user.js。