首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在sequelize中更新事务中的关联模型

如何在sequelize中更新事务中的关联模型
EN

Stack Overflow用户
提问于 2020-12-09 16:39:22
回答 2查看 581关注 0票数 0

我有两张桌子,专家和行业。每个专家都属于多个行业,如何在一次交易中更新他们?

我知道setter方法可以在没有事务处理的情况下更新关联,我需要它执行得更健壮。

代码语言:javascript
复制
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})
    })

}
EN

回答 2

Stack Overflow用户

发布于 2020-12-14 13:30:06

你的问题有点模棱两可,我不完全明白你想用indusries做什么,因为它什么也没做。但我得到了最新的部分。

我认为你应该查询两次,一个是更新专家模型,另一个是行业。

尝尝这个,

代码语言:javascript
复制
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
    }
})
票数 0
EN

Stack Overflow用户

发布于 2020-12-15 13:49:51

belongstoMany的源代码用belongs-to-many.js编写

通过传递实例数组或其主键来设置关联的模型。它不在传递的数组中的所有内容都将被取消关联。

@param {模型}对象源实例,用于将新实例与@param {Model|Model[]|string[]|string|number[]|number} newAssociatedObjects关联单个实例或主键,或持久实例或主键的混合数组@param {Object}选项传递给through.findAllbulkCreateupdatedestroy @param {Object} options.validate为联接模型@param {Object} options.through连接表的其他属性运行验证。set(sourceInstance,newAssociatedObjects,options)

因此,您可以将一个事务处理实例传递到此method.In中,我的情况是

代码语言:javascript
复制
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})
    })

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65213282

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档