Emanuela Colta
Emanuela Colta

Reputation: 2207

How to establish Many-to-Many relationship between tables with Sequelize.js?

I want to establish a Many-to-Many relationship between Events table and Users table, by using Sequelize.js. A user can participate to more events and one event has more participants. Therefore, I brought an intermediate table of event_user and I created its model.

Here are all the 3 models:

My users_model.js:

var EventUser = require('./event_user_model.js');

//_______________________Init & Config Sequelize__________________

const Sequelize = require("sequelize");
const sequelize = new Sequelize('db', 'root', '', {
  host: 'localhost',
  dialect: 'mysql',
  pool: {
    max: 5,
    min: 0,
    idle: 10000
  }
});
//____________Declare table structure ________________________

var User = sequelize.define('user', {
  id: {
    type: Sequelize.STRING,
    primaryKey: true, 
    },
  password: { 
    type: Sequelize.STRING,
  },
  email: {
    type: Sequelize.STRING
  },   
  user_id: { //Foreign Key. Do I even need to put it here at all?
    type: Sequelize.INTEGER,
    references: {
      model: "events_user",
      key: "user_id",
     } 
  },

}, {
  freezeTableName: true
});

//__________________Establish relationships with other tables_________


User.belongsTo(EventUser,{foreignKey:user_id});

//_____________________________________________________________________

User.sync({force:true}).then(function () {
  return User.create({
    id:'ORD0',
    password: 'mypass',
    email: 'whatever@gmail.com',
    user_id:1    
  });
}).then(c => {
    console.log("User Created", c.toJSON());
})
.catch(e => console.error(e));

//______________________________________________________________________

module.exports = User;

My events_model.js:

var EventUser = require('./event_user_model.js');

//______________Init & Config Sequelize_________
const Sequelize = require("sequelize");
const sequelize = new Sequelize('millesime_admin', 'root', '', {
  host: 'localhost',
  dialect: 'mysql',
  pool: {
    max: 5,
    min: 0,
    idle: 10000
  }
});
//______________________Declare table structure __________________

var Event = sequelize.define('event', {    
  eventid: { 
    type: Sequelize.INTEGER,
    primaryKey: true, 
    autoIncrement: true,        
    },
  date: {
    type: Sequelize.DATE
  },
  title: {
    type: Sequelize.STRING,
  },   
  event_id: { //Foreign Key . Do I even need to put it here at all?
    type: Sequelize.INTEGER,
    references: {
      model: "event_user",
      key: "event_id" // Surely here I do something wrong!!
    }
  },     

}, {
  freezeTableName: true 
});

//____________Establish relationships with other tables_________

Event.belongsTo(EventUser, {foreignKey: event_id});

//________________________Create table____________
Event.sync().then(function () {

  return Event.create({
    eventid:1,
    title: 'Event1',
    date: new Date(24, 9, 2016),
    event_id: 1,        
  });
}).then(c => {
    console.log("Created event", c.toJSON());
}).catch(e => console.error(e));

//________________________________________________________
    module.exports = Event; 

And my event_user_model.js:

var User = require('./users_model.js');
var Event= require('./events_model.js');

//______________________________Initialize & Config Sequelize__________________
const Sequelize = require("sequelize");
const sequelize = new Sequelize('millesime_admin', 'root', '', {
  host: 'localhost',
  dialect: 'mysql',
  pool: {
    max: 5,
    min: 0,
    idle: 10000
  }
});
//_______________Declare table structure ________________________
var EventUser = sequelize.define('eventuser', {    
  eventuserid: { 
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    },
  user_id: {
    type: Sequelize.INTEGER,
    references: {
      model: "users",
      key: "id",
     }   
  },
  event_id: { 
    type: Sequelize.INTEGER,
    references: {
       model: "event",
       key: "eventid",
     }   
  },
 reservationConfirmation:{
    type:Sequelize.BOOLEAN,
 },
 attendance:{
    type:Sequelize.BOOLEAN
 },
},
{
  freezeTableName: true 
});

//___________________Establish relationships with other tables_________

EventUser.hasMany(User, {foreignKey:id});
//EventUser.hasMany(Event, {forignKey:eventid});
//__________________________Create table_______________________
EventUser.sync( /*{force: true}*/ ).then(function () {
  return EventUser.create({
    eventuserid:1,
    event_id:1,
    user_id: 1,
    reservationConfirmation: true,
    attendance: true    
  });
}).then(c => {
    console.log("Created", c.toJSON());
}).catch(e => console.error(e));   
//___________________________________________________
 module.exports = EventUser;

Upvotes: 2

Views: 5657

Answers (2)

piotrbienias
piotrbienias

Reputation: 7411

First wrong thing that you do is to create new Sequelize instance at each model file. You need to create a single file in which you create sequelize instance, which will be imported in every model definition file. In your case, the structure can be as follows

- models
    - sequelize.js
    - event.js
    - user.js
    - eventUser.js

And each file should be like that:

// sequelize.js
var Sequelize = require('sequelize');

var sequelize = new Sequelize(
    'millesime_admin',
    'root',
    '',
    {
        host: 'localhost',
        dialect: 'mysql',
        pool: {
            max: 5,
            min: 0,
            idle: 10000
       }
    }
);

module.exports = sequelize;

Now, when you have the sequelize instance created, you can define models

// event.js
var sequelize = require('./sequelize');

var Event = sequelize.define(...);

module.exports = Event;

// user.js
var sequelize = require('./sequelize');

var User = sequelize.define(...);

module.exports = User;

Now you are able to create the last model EventUser, as well as many-to-many relation between Event and User. This relation will be created in the eventUser.js file where the EventUser model definition happens

// eventUser.js
var sequelize = require('./sequelize');
var User      = require('./user');
var Event     = require('./event');

var EventUser = sequelize.define(...);

User.belongsToMany(Event, { through: EventUser } );
Event.belongsToMany(User, { through: EventUser } );

Upvotes: 2

rsp
rsp

Reputation: 111506

See BelongsToMany mixin: "Many-to-many association with a join table."

Example:

UserProject = sequelize.define('user_project', {
  role: Sequelize.STRING
});
User.belongsToMany(Project, { through: UserProject });
Project.belongsToMany(User, { through: UserProject });    

See the docs:

Upvotes: 1

Related Questions