简体   繁体   中英

Sequelize update with association

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

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

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

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

First find Model and connect Assosiations then make changes and call save() function to update 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');
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM