问题描述
我正在与sequelize建立一对多关联.当两个模型都定义在同一文件中时,大多数教程和文档都会显示示例.我目前有两个文件,第一个city.js:
I am working on one to many assocations with sequelize. Most tutorials and documentation shows examples when both models are defined in the same file.I currently have two files, first 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:
And a second file 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;
当我导入两个模块并尝试实例化对象时:
When I import both modules and try to instantiate object:
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');
});
我收到以下错误:
是在从模型导出模型之前对模型进行了预定义的问题还是我遗漏了某些东西?
Is the problem that models are promisified before they are exported from model or am I missing something?
推荐答案
我不确定您的代码到底有什么问题,请确定是否需要运行它.
I'm not sure what exactly is the problem with your code, would need to run it to be sure.
但是,当您在寻找示例时,请从续集Github .
But as you were looking for an example, take a look at this example from Sequelize Github.
它在不同文件中声明模型,并将它们与index.js
关联.
It declares models in different files and associate them in the index.js
.
稍后,您可以使用简单的model
属性 model.Country
:
Later you can reference your other model with a simple model
atribute model.Country
:
City.belongsTo(model.Country, {foreignKey : 'countryId', as: 'Country'});
例如 user.js .
这篇关于将多个文件中的一对多关联化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!