我有两张桌子,专家和行业。每个专家都属于多个行业,如何在一次交易中更新他们?
我知道setter方法可以在没有事务处理的情况下更新关联,我需要它执行得更健壮。
Expert.belongstoMany(Industry,{through:"expert_industry"})
async function updateExpert(data) {
const expert = await Expert.findByPk(data.id, {
include: [
{
model: Industry,
through: {
attributes: []
}
}
]
})
const industries = Industry.findAll({
where: {
id: data.industry_id
}
})
expert.setIndustry(industries)
// Here I want update expert and its industry in a transcation, How to do it ?
return sequelize.transaction(t => {
// The sql to insert or delete table expert_industry doesn't appear in this transcation
// and I don't know which should be the owner of update function, Expert(model) or the expert(instance)?
return Expert.update(data, {transaction: t})
})
}发布于 2020-12-14 13:30:06
你的问题有点模棱两可,我不完全明白你想用indusries做什么,因为它什么也没做。但我得到了最新的部分。
我认为你应该查询两次,一个是更新专家模型,另一个是行业。
尝尝这个,
return sequelize.transaction(t => {
try{
await Expert.update(data, { transaction: t })
//you should add where option, otherwise your whole rows are gonne be updated
await Industry.update(data, { transaction: t, where : { expertId : data.id } })
//expertId should be your foreign key
}
catch(e){
throw e
}
})发布于 2020-12-15 13:49:51
belongstoMany的源代码用belongs-to-many.js编写
通过传递实例数组或其主键来设置关联的模型。它不在传递的数组中的所有内容都将被取消关联。
@param {模型}对象源实例,用于将新实例与@param {Model|Model[]|string[]|string|number[]|number} newAssociatedObjects关联单个实例或主键,或持久实例或主键的混合数组@param {Object}选项传递给through.findAll、bulkCreate、update和destroy @param {Object} options.validate为联接模型@param {Object} options.through连接表的其他属性运行验证。set(sourceInstance,newAssociatedObjects,options)
因此,您可以将一个事务处理实例传递到此method.In中,我的情况是
Expert.belongstoMany(Industry,{through:"expert_industry"})
async function updateExpert(data) {
const expert = await Expert.findByPk(data.id, {
include: [
{
model: Industry,
through: {
attributes: []
}
}
]
})
const industries = Industry.findAll({
where: {
id: data.industry_id
}
})
return sequelize.transaction(t => {
// You could pass transcation instance into the setter method
expert.setIndustry(industries,{transcation:t})
return Expert.update(data, {transaction: t})
})
}https://stackoverflow.com/questions/65213282
复制相似问题