2017-08-09 15 views
0

後継では、新しく作成したモデルに既存のエントリを追加して新しいモデルを取得できますか?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メソッドの一部として私は既に存在するユーザーをシミュレートしています。

答えて

0

私はこの使用して非同期を実装するため、わずかにクリーンな方法を見つけました:

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 
} 
関連する問題