在多个文件中对一个到多个关联进行续订

Ron*_*ker 4 node.js sequelize.js bluebird

我正在与sequ​​elize进行一对多的关联.大多数教程和文档都显示了在同一文件中定义两个模型的示例.我目前有两个文件,第一个是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;
Run Code Online (Sandbox Code Playgroud)

第二个文件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;
Run Code Online (Sandbox Code Playgroud)

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

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');
});
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

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

模型在从模型导出之前是否会被宣传,或者我遗漏了什么?

Den*_*edo 6

我不确定你的代码究竟是什么问题,需要运行它才能确定.

但是当你在寻找一个例子时,请看一下Sequelize Github的这个例子.

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

稍后您可以使用简单的model属性引用其他模型model.Country:

City.belongsTo(model.Country, {foreignKey : 'countryId', as: 'Country'});
Run Code Online (Sandbox Code Playgroud)

例如,user.js.