Javascript 使用关联进行后续更新

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33918383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:39:28  来源:igfitidea点击:

Sequelize update with association

javascriptmysqlnode.jssequelize.js

提问by Jacob

In sequelize it's possible to create a row and all it's association in one go like this:

在 sequelize 中,可以像这样一次性创建一行及其所有关联:

return Product.create({
  title: 'Chair',
  User: {
    first_name: 'Mick',
    last_name: 'Broadstone'
  }
}, {
  include: [ User ]
});

Is there a equivalent for update? I tried

是否有等价的更新?我试过

model.user.update(req.body.user, {where: {id: req.user.user_id}, include: [model.profile]})

But it's only updating user

但它只是更新用户

Doing this for create works

这样做是为了创作作品

model.user.create(user, {transaction: t, include: [model.profile]})

采纳答案by mabc224

First you have to find model including sub model which you want to update. then you can get reference of sub model to update easily. i am posting an example for your reference. hope it will help.

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

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

回答by Marcin

If you want to update both models(Product & Profile) at once. One of the approaches can be:

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

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

回答by Abraham George

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

Here positon belongsToMany job

这里的位置属于多个工作