首页 > 解决方案 > AdonisJS 关联多个 oneToMany 关系

问题描述

如何在 Adonis 中关联 oneToMany 关系中的值数组。

文档显示以下内容以关联单个值

const Profile = use('App/Models/Profile')
const User = use('App/Models/User')

const user = await User.find(1)
const profile = await Profile.find(1)

await profile.user().associate(user)

如果我的表单提交了一个包含多个用户 ID 的数组,我知道我可以使用 array.map 并遍历每个用户 ID,但这是一个异步命令,我的控制器会在 map 完成之前尝试响应客户端。

users.map(async (u)=>{
  let user = await User.find(u)
  await profile.user().associate(user)
})

return //I think this would return before the above map function completed.

标签: javascriptarraysadonis.jsassociate

解决方案


你可以用 for 来做到这一点

for (const u of users) {
    const user = await User.find(u)
    await profile.user().associate(user)
}

推荐阅读