使用Sequelize.js更新关联

时间:2016-12-30 13:43:41

标签: node.js sequelize.js

我正在尝试使用sequelize.js更新关联。

我试过在stackoverflow上举例说明以下链接:

Sequelize update with association Sequelize update with association Updating attributes in associated models using Sequelize

所有这些链接都没有让我实现我想要实现的目标。 我的模型如下,我有一个国家模块和一个城市模块。一个国家有很多城市。请参考下面的模块。 请指教。

country.js文件

module.exports = function (sequelize, DataTypes) {
    var country= sequelize.define('COUNTRY', {
        COUNTRY_ID: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            autoIncrement: true

        },
        COUNTRY_NAME: DataTypes.STRING,
        COUNTRY_CURRENCY: DataTypes.STRING

    }, {
        freezeTableName: true,
        classMethods: {
            associate: function (models) {

                COUNTRY_ID.hasMany(models.CITIES, {

                    foreignKey: 'COUNTRY_ID'
                })


            }
        },
         instanceMethods: {
            updateAssociation: function (onSuccess, onError) {
                country.findAll({

                        where: {
                             COUNTRY_ID: req.params.country_id
                     },
                       include: [
                          {
                              model: sequelize.import('./cities.js'), 
                          }
                        ]

                    })

                    })
                    .then(country =>{
                    const updatePromises = country.map(countries =>{
                        return countries.updateAttributes(req.body);
                    });
                    const updatePromisescities = list.CITY.map(cities =>{
                    return cities.updateAttributes(req.body.CITYs[0]);

                   });
                    return sequelize.Promise.all([updatePromises, updatePromisescities ])
                  }).then(onSuccess).error(onError);           
                }

        }
    });
    return country;
};

city.js档案

module.exports = function (sequelize, DataTypes) {
    var CITY = sequelize.define('LIST_CODE', {
        CITY_ID: {
            type: DataTypes.INTEGER,
            primaryKey: true
        },
        COUNTRY_ID: {
            type: DataTypes.INTEGER,
            primaryKey: true
        }
    }, {
        freezeTableName: true,
        timestamps: false,
        classMethods: {
            associate: function (models) {
                // associations can be defined here

                CITY.belongsTo(models.COUNTRY, {

                    foreignKey: 'COUNTRY_ID'
                })
            }
        }

});
    return CITY;
};

0 个答案:

没有答案