Sequelize update with association

46,201

Solution 1

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

Solution 2

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!`))
Share:
46,201
Jacob
Author by

Jacob

Getting badge

Updated on May 11, 2021

Comments

  • Jacob
    Jacob almost 3 years

    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]})
    
  • Jacob
    Jacob over 8 years
    This seems to be the best solution for updating
  • Shahar Hadas
    Shahar Hadas about 7 years
    The only issue I'm seeing with this approach is you assume no other request will update the original filtered object.
  • Andy
    Andy over 5 years
    Whether that is necessary depends on your business logic requirements, and it can be prevented by using a SERIALIZABLE or REAPEATABLE READ transaction.
  • Catfish
    Catfish over 5 years
    Doesn't look like updateAttributes is a function in version 4 docs.sequelizejs.com/class/lib/model.js~Model.html
  • KIRAN K J
    KIRAN K J over 2 years
    updateAttributes is not found. Which is the latest way
  • Yogita Bhatia
    Yogita Bhatia almost 2 years
    This solution might not work as it's specifically mentioned in the sequelize docs that Model.save() is unaware of the associations and hence it won't be saving any child updates. Refer - sequelize.org/docs/v6/core-concepts/assocs/…