javascriptarraysadonis.jsassociate

AdonisJS Associate with multiple oneToMany relationships


How do I associate an array of values from a oneToMany relationship in Adonis.

The docs show the following to associate a single value

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)

What if my form had submitted an array of multiple user id's I know I could use array.map and loop over each one, but that is an asynchronous command and my controller would try to respond to the client before map had completed.

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.

Solution

  • You can do it with a for of

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