sequelize create + EmiratesToMany关联+通过

时间:2019-01-06 16:55:29

标签: associations sequelize.js has-and-belongs-to-many model-associations

尝试创建一个实例,并在一个命令中将所需的实例与其他行数据相关联

A.belongsToMany(B, through: models.AB)
B.belongsToMany(A, through: models.AB)
define('AB', {
  c: STRING,
  d: STRING,
  e: INTEGER
});

行应该这样结束:

a_id | b_id | c | d | e | 1 | 1 | 'text' | 'text' | 94 |

现在我必须通过2个步骤和一个迭代来完成它:

let a = await models.A.create({
  x: 'value'
});
let associationArrayOfB = [{b: 1, c: 'text', d: 'text', e: 94}, {...}]
associationArrayOfB.forEach(object => {
  a.addB(object, {
    through: {
      c: object.c
      d: object.d
      e: object.e
    }
  })
});

甚至可以执行1条命令吗?

当前我迷路了:

let result = await models.A.create({
  ...ctx.request.body,
  b: associationArrayOfB.map(object => {
    let {b, c, d, e} = object;
      return {
        b_id: b,
        through: {
          c,
          d,
          e
        }
      }
    })
  }, {
    include: [ models.B ]
  }));

请帮助

0 个答案:

没有答案