如何使用 sequelize 构建属于多个关联的模型 [英] How to build model with sequelize for belong to many association
问题描述
这是我在 Country.js 中写的(除了数据类型与 User.js 完全相同):
This is what I wrote in Country.js (exactly the same as User.js except datatypes) :
module.exports = function(sequelize, DataTypes) {
const Country = sequelize.define('country',
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
code: {
type: DataTypes.INTEGER
},
alpha2: {
type: DataTypes.STRING
},
alpha3: {
type: DataTypes.STRING
},
name_en: {
type: DataTypes.STRING
},
name_fr: {
type: DataTypes.STRING
}
},
{
freezeTableName: true,
timestamps: false
});
Country.associate = ( models ) => {
models.Country.belongsToMany(models.User, {
through: 'country_user',
as: 'user',
foreignKey: 'id_country'
});
};
return Country;
}
这是我的查询:
router.get('/thisuserCountries', function(req, res, next){
User(db, Sequelize.DataTypes).findOne({
include: [{
model: Country(db, Sequelize.DataTypes),
as: 'countries',
required: false,
attributes: ['id'],
}],
where: {
email: 'jerome.charlat@gmail.com'
}
})
.then(user => {
if(user) {
res.json(user)
}
else {
res.send('User does not exist')
}
})
.catch(err => {
res.send('error: ' + err)
})
})
这是我的 db.js :
This is my db.js :
const Sequelize = require('sequelize')
const db = new Sequelize('travel_memories', 'root', '', {
host: 'localhost',
dialect: 'mysql',
port: 3306
})
db
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
const models = {
Country: db.import('../models/Country'),
User: db.import('../models/User'),
CountryUserJoin: db.import('../models/Country_user')
};
Object.keys(models).forEach((modelName) => {
if('associate' in models[modelName]){
models[modelName].associate(models);
}
});
module.exports = db
邮递员说:错误 SequelizeEagerLoadingError:国家与用户无关!
Postman says : error SequelizeEagerLoadingError: country is not associated to user!
但是,我认为当我关联每个模型中的表时,我应该在模型 User_country 的直通参数中写入.所以我试着写一些类似的东西:
But, I think I should write in the through parameter the model User_country when I associate tables in each model. So i tried to write something like :
Country.associate = ( models ) => {
models.Country.belongsToMany(models.User, {
through: models.Country_user,
as: 'user',
foreignKey: 'id_country'
});
};
当我启动服务器时,控制台会在查询任何内容之前说:
And console says when I launch server, before querying anything :
SequelizeAssociationError: country.belongsToMany(user) 需要通过选项,传递字符串或模型.
SequelizeAssociationError: country.belongsToMany(user) requires through option, pass either a string or a model.
所以我被屏蔽了.我使用文档中的示例来编写与 models.foo 的关联.但实际上模型无处可去..
So I am blocked. I used the example in documentation to write the assocation with models.foo. But in fact models comes from nowhere..
再次感谢您的帮助!
推荐答案
关于这个的文档并不多,但是 here 它说在查询或选择属于多属性时应该使用 through
选项,就像这样:
There's not a lot of documentation about this, but here it says that you should use a through
option when querying or selecting belongs-to-many attributes, just like this:
...
User(db, Sequelize.DataTypes).findOne({
include: [{
model: Country(db, Sequelize.DataTypes),
as: 'countries',
required: false,
through: {
attributes: ['id']
}
}],
where: {
email: 'jerome.charlat@gmail.com'
}
})
...
这篇关于如何使用 sequelize 构建属于多个关联的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!