gpt4 book ai didi

sequelize.js - Sequelize 和创建新的持久化实例中的关联

转载 作者:行者123 更新时间:2023-12-03 22:39:34 25 4
gpt4 key购买 nike

module.exports = (sequelize, DataTypes) => {
let City = sequelize.define('City', {
id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
name: {type: DataTypes.STRING, allowNull: false, unique: true},
});
City.associate = (models) => {
City.belongsTo(models.Country);
};
return City;
}

module.exports = (sequelize, DataTypes) => {
let Country = sequelize.define('Country', {
id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
code: {type: DataTypes.STRING, allowNull: false, unique: true },
name: DataTypes.STRING
});
Country.associate = (models) => {
Country.hasMany(models.City);
};
return Country;
}

我有以上型号。现在,当我创建 City 时,我正在这样做。
let country = await Country.findById(input.countryID);
if(country) {
let city = await City.create({
name: input.name
});
await city.setCountry(country);

callback(null, city);
} else {
callback(new Error('Country does not exist'));
}

有没有一种方法可以在一个查询中直接创建与国家关联的城市,而不是为创建城市和在城市中设置国家进行多次查询?此外,我想在城市创建后填充响应以使其结果也包含国家。

最佳答案

你可以简单地做到这一点:

City.create({
name: input.name ,
country_id : input.countryID
}).then((data) => { // <----- Inserted if country_id exist in country table as per primary foreign key rule
// Code for success
}).catch(err => { // Will throw error if condition doesn't match
// Code for Error
})

关于sequelize.js - Sequelize 和创建新的持久化实例中的关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51651788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com