Sequelize update with association

后端 未结 3 1887
有刺的猬
有刺的猬 2020-12-15 15:58

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_na         


        
3条回答
  •  萌比男神i
    2020-12-15 16:53

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

提交回复
热议问题