关联并创建新的持久实例

时间:2018-08-02 10:50:53

标签: sequelize.js

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'));
}

除了通过多个查询来创建城市并在城市中设置国家/地区之外,还有一种方法可以在一个查询中直接创建与国家/地区相关联的城市?我也想在城市创建后填充响应,以使结果也包含国家/地区。

1 个答案:

答案 0 :(得分:0)

您可以轻松做到这一点:

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
})