[英]Sequelize update with association
在 sequelize 中,可以像這樣一次性創建一行及其所有關聯:
return Product.create({
title: 'Chair',
User: {
first_name: 'Mick',
last_name: 'Broadstone'
}
}, {
include: [ User ]
});
是否有等價的更新? 我試過
model.user.update(req.body.user, {where: {id: req.user.user_id}, include: [model.profile]})
但它只是更新用戶
這樣做是為了創作作品
model.user.create(user, {transaction: t, include: [model.profile]})
首先,您必須找到包含要更新的子模型的模型。 那么你可以輕松獲得子模型的參考。 我發布了一個示例供您參考。 希望它會有所幫助。
var updateProfile = { name: "name here" };
var filter = {
where: {
id: parseInt(req.body.id)
},
include: [
{ model: Profile }
]
};
Product.findOne(filter).then(function (product) {
if (product) {
return product.Profile.updateAttributes(updateProfile).then(function (result) {
return result;
});
} else {
throw new Error("no such product type id exist to update");
}
});
如果要立即更新兩個模型(產品和配置文件)。 其中一種方法可以是:
// this is an example of object that can be used for update
let productToUpdate = {
amount: 'new product amount'
Profile: {
name: 'new profile name'
}
};
Product
.findById(productId)
.then((product) => {
if(!product) {
throw new Error(`Product with id ${productId} not found`);
}
product.Profile.set(productToUpdate.Profile, null);
delete productToUpdate.Profile; // We have to delete this object to not reassign values
product.set(productToUpdate);
return sequelize
.transaction((t) => {
return product
.save({transaction: t})
.then((updatedProduct) => updatedProduct.Profile.save());
})
})
.then(() => console.log(`Product & Profile updated!`))
await Job.update(req.body, {
where: {
id: jobid
}
}).then(async function () {
await Job.findByPk(jobid).then(async function (job) {
await Position.findOrCreate({ where: { jobinput: req.body.jobinput } }).then(position => {
job.setPositions(position.id)
})
})
這里positon屬於ToMany工作
首先找到模型並連接關聯,然后進行更改並調用 save() 函數來更新值
db.User.findOne({
where:{id:req.User.id},
include:[{
model:db.Task,
as:'Task'
}]
}).then(User=>{
User.Task.title='Task Title'
User.save();
res.json(User); //or res.json('ok updated');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.