通过关联续订更新

时间:2015-11-25 13:57:24

标签: javascript mysql node.js sequelize.js

在续集中,可以像这样一次创建一行和所有它的关联:

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

4 个答案:

答案 0 :(得分:8)

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

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

答案 1 :(得分:2)

如果要一次更新两个型号(产品和配置文件)。方法之一可以是:

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

答案 2 :(得分:0)

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

这里positon属于对很多工作

答案 3 :(得分:0)

首先找到模型并连接关联,然后进行更改并调用 save() 函数来更新值

 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');
        });
相关问题