'How to add to junction table?

I have three tables users, projects and my junction table user_projects

I did this association on sequelize

User.belongsToMany(Project, { through: User_Project });

enter image description here

This works (ignoring unneeded properties)

  const thomas = await User.create({
    username: "thomas",
    email: "[email protected]",
    password: "123456",
  });


  const projectOne = await Project.create({
    createdBy: thomas.id,
  })

  await thomas.addProject(projectOne)

However, Is there a way to do this with just the userId ?

For example, given id=10 I want to create a project as well as add that into the junction table

  // create the project
  const projectOne = await Project.create({
    createdBy: 10,
  })

  // how to add to junction table?


Solution 1:[1]

If you have a defined junction table model then just use its create method:

const projectOne = await Project.create({
    createdBy: thomas.id,
})
const userProjectRecord = await User_Project.create({
  userId:thomas.id,
  projectId: projectOne.id
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anatoly