使用关联进行后续更新

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

这里的职位属于多份工作

首先找到Model并连接Assosiations,然后进行更改并调用save()函数更新Values

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