मेरा समाधान।
विधि जोड़ें updateOrCreate
Product.updateOrCreate = function (options) {
return this.findOrCreate(options).then(res => {
let [row, created] = res;
if (created) return [row, created];
return row.update(options.defaults, options.transaction)
.then(updated => [updated, created]);
})
};
Tag.updateOrCreate = function (options) {
return this.findOrCreate(options).then(res => {
let [row, created] = res;
if (created) return [row, created];
return row.update(options.defaults, options.transaction)
.then(updated => [updated, created]);
})
};
उपयोग करें
let data = {
title: 'Chair',
tag: [
{name: 'Alpha'},
{name: 'Beta'}
]
};
return sequelize.transaction().then(t => {
return Product.updateOrCreate({
where: {title: data.title},
defaults: data,
transaction: t
}).then(res => {
let [product] = res;
return Promise.all(data.tag.map(tag => {
return Tag.updateOrCreate({
where: {name: tag.name},
defaults: tag,
transaction: t
}).then(res => {
let [tag] = res;
return Promise.resolve(tag);
}).catch(err => Promise.reject(err.message));
})).then(() => {
t.commit();
sequelize.close();
}).catch(err => Promise.reject(err));
}).catch(err => {
t.rollback();
sequelize.close();
});
});