通过关联续订更新 [英] Sequelize update with association

查看:66
本文介绍了通过关联续订更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在续集中,可以像这样创建一行及其所有关联:

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

但它只是更新用户

为创建作品执行此操作

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

这篇关于通过关联续订更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆