[英]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.