2017-08-09 109 views
0

在續集中,是否有方法將現有條目添加到新創建的模型並獲取新模型?將現有條目添加爲新創建條目的關聯並獲取新創建/更新條目

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 
}