15

I have projects and users.

A user can have many projects.

A project can have multiple users.

I tried to model this with a belongsToMany association.

On my server I defined the associations like this:

user.belongsToMany(project, {
  through: 'writer_of_project'
  foreign-key: 'user'
  as: 'projects'
});

project.belongsToMany(user, {
  through: 'writer_of_project'
  foreign-key: 'project'
  as: 'writers'
});

On my client it looks like this:

user: {
  id:     1,
  ...
  projects: [1,2,3]
}

project: {
  id:     1,
  ...
  writers: [1,4,5]
}

On the server the association requires a third table to store the association and Sequelize doesn't seem to let me include the corresponding models from it.

If I run a project.find(1) with include:[user] I get

user is not associated with project!

If I try to put the project from the example above into the update method, the users attribute is simply ignored (I expected a project.setUsers(projectUpdate.users to happen in the background).

What is the right way to deal with the loading and updating of these associations?

snoob dogg
  • 2,491
  • 3
  • 31
  • 54
K..
  • 4,044
  • 6
  • 40
  • 85
  • 1
    I find that if you set up your models with the [sequelize-cli](https://www.npmjs.com/package/sequelize-cli) then association become easier to read as they are included within the model itself. It also allows you to use migrations which it a real bonus – swifty Apr 17 '15 at 08:28

1 Answers1

26

When you provide an alias (as) to the association, you need to provide that to the include as well:

project.belongsToMany(user, {
  through: 'writer_of_project'
  foreign-key: 'project'
  as: 'writers'
});

project.find({
  where: { id: 1 },
  include: [ { model: User, as: 'writers' } ]
});

Or you could save the association:

Project.writersAssociation = project.belongsToMany(user, {
  through: 'writer_of_project'
  foreign-key: 'project'
  as: 'writers'
});

project.find({
  where: { id: 1 },
  include: [ project.writersAssociation ]
});
Sandro Munda
  • 39,921
  • 24
  • 98
  • 123
Jan Aagaard Meier
  • 28,078
  • 8
  • 95
  • 66
  • 1
    In doing so will that create a writer_of_project model along with a corresponding table in the database? Sorry to piggy back on this but I'm concerned that my migration did not create a writer_of_project table within the db. Please advice.... – Tyler Canton Feb 24 '17 at 16:40