【问题标题】:Sequelize update with associationSequelize 更新与关联
【发布时间】:2021-05-10 21:13:22
【问题描述】:

在 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]})

【问题讨论】:

  • 在纯 SQL 中会如此简单...

标签: javascript mysql node.js sequelize.js


【解决方案1】:

首先,您必须找到模型,包括要更新的子模型。 然后您可以轻松获取子模型的参考以进行更新。 我发布了一个示例供您参考。希望它会有所帮助。

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");
  }
});

【讨论】:

  • 这似乎是更新的最佳方案
  • 我在这种方法中看到的唯一问题是您假设没有其他请求会更新原始过滤对象。
  • 是否有必要取决于您的业务逻辑要求,可以通过使用SERIALIZABLEREAPEATABLE READ 事务来防止。
  • 看起来不像 updateAttributes 是版本 4 中的函数 docs.sequelizejs.com/class/lib/model.js~Model.html
  • updateAttributes 未找到。这是最新的方法
【解决方案2】:

如果您想同时更新两个模型(产品和配置文件)。其中一种方法可以是:

// 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!`))

【讨论】:

    【解决方案3】:
    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)
              })
    })
    

    这里的职位属于ToMany工作

    【讨论】:

      【解决方案4】:

      首先找到模型并连接关联然后进行更改并调用 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');
              });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-11
        • 2012-11-24
        相关资源
        最近更新 更多