Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Sequelize belongsToMany associations?

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?

like image 544
K.. Avatar asked Apr 16 '15 16:04

K..


People also ask

How do I use Sequelize associations?

Creating associations in sequelize is done by calling one of the belongsTo / hasOne / hasMany / belongsToMany functions on a model (the source), and providing another model as the first argument to the function (the target). hasOne - adds a foreign key to the target and singular association mixins to the source.

How do you associate two models in Sequelize?

exports = function(sequelize, DataTypes) { var Session = sequelize. define("Session", { success: { type: DataTypes. BOOLEAN, allowNull: false, default: false }, TeammateId: { type: DataTypes. INTEGER, allowNull: false } }, { classMethods: { associate: function(models) { Session.

How do you create a one to many relationship in Sequelize?

To create a One-To-Many relationship, the hasMany and belongsTo associations are used together; To create a Many-To-Many relationship, two belongsToMany calls are used together.


1 Answers

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 ]
});
like image 166
Jan Aagaard Meier Avatar answered Oct 21 '22 09:10

Jan Aagaard Meier