Sequelize将现有条目添加为与新创建的条目的关联,并获取新创建/更新的条目

时间:2017-08-09 07:57:14

标签: node.js postgresql sequelize.js

在sequelize中,有没有办法将现有条目添加到新创建的模型中并获得新模型?

const Account = sequelize.define('Account')
const User = sequelize.define('User')

Account.associate = (models) => {
  Account.belongsToMany(models.User, { through: 'UserAccount' })
}

User.associate = (models) => {
  User.belongsToMany(models.Account, { through: 'UserAccount' })
}

Promise.all([User.create(), Account.create()])
  .spread((user, account) => account.addUsers([user.id])
  .then(userAccounts => {
     // Right now I have the userAccounts, but I want the updated account 
  }

是否有干净的方法来执行此操作,而不是保存帐户创建的承诺并再次查找帐户,如下所示:

const accountPromise = Account.create()
Promise.all([User.create(), accountPromise])
   .spread((user, account) => account.addUsers([user.id])
   .then(() => accountPromise)
   .then((account) => Account.findById(account.id, { include: 'Users' })
   .then(account) => {
      // this is what I want
   }

请注意,我不希望将用户创建为Account.create方法的一部分。我正在模拟已经存在的用户。

1 个答案:

答案 0 :(得分:0)

我找到了一种使用async实现此方法的更简洁的方法:

const createAccountWithUsers = async (userIds) => {
  // userIds is an array like [1, 2, 3]
  let account = await Account.create()
  await account.addUsers(userIds)
  account = await Account.findById(account.id, {include: 'Users'})

  // you now have an account object with the added user
  return account
}