2016-04-26 76 views
1

我正在研究一個到多個關聯的續集。大多數教程和文檔都會顯示兩個模型在同一個文件中定義的示例。 我現在有兩個文件,一是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'); 
}); 

我收到以下錯誤:

throw new Error(this.name + '.' + Utils.lowercaseFirst(Type.toString()) + ' called with something that\'s not an instance of Sequelize.Model')

模型在從模型中導出之前是否已被promisified問題還是我錯過了某些東西?

回答

1

我不確定你的代碼究竟是什麼問題,需要運行它才能確定。

但是,當你正在尋找一個例子,看看這個例子從Sequelize Github

它將模型聲明在不同的文件中並將它們關聯到index.js中。

以後你可以用一個簡單的model屬性附加傷害model.Country引用您的其他型號:

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

例如,user.js

+1

謝謝你,有一點index.js修改我得到了我想要的結果 –