update model and association in sequelize

时间:2018-03-23 00:48:46

标签: node.js sequelize.js

To have a vague idea, having a model "Account"

const Chars = require('./chars');
const Account = sequelize.define('account', {
 ...
}
Account.hasMany(Chars, { as: 'chars', foreignKey: 'accountId' });

table chars is like:

id |charId     |accountId  |ival          |bval
28 |1          |90         |0             |null
29 |2          |90         |0             |null
30 |3          |90         |200           |null
31 |4          |90         |null          |true
32 |5          |90         |null          |false
33 |6          |90         |null          |false

so "account" has many "chars" but need them to update at once (if possible)

just need some guidance to made a proper update to the account model and rows for table "chars" (association) using sequelize.

should I use some "foreach" ? maybe a "bulkUpdate" ?

1 个答案:

答案 0 :(得分:0)

您需要立即更新单个帐户的所有字符吗?使用这样的东西:

Chars.update(
  {
    ival: 0, // put your value here
    bval: 0, // put your value here
  },
  { 
    where: { 
      accountId: myAccountId, // put your id here 
    } 
  }
);

如果您的意思是希望帐户及其所有关联的字符一次更新 - 那么,您不能在单个查询中执行此操作。您需要一个查询来更新帐户,另一个查询需要更新字符。