Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize Many to Many - How to create a new record and update join table

I'm building a simple database with node, express and sequelize. I have created my models, and sequelize created the tables in my database.

I have the models User and City, with a many to many relationship. Sequelize created the tables Users, Cities and a join table CitiesUsers: with UserId and CityId.

My question is when I create a new user how do I update that join table? The CityId property gets ignored on create.

   //Models use     //City.hasMany(User);    //User.hasMany(City);     var user = User.build({       first_name: 'John',       last_name: 'Doe',       CityId: 5     });      user.save(); 
like image 989
RickTakes Avatar asked Mar 03 '15 00:03

RickTakes


People also ask

Does Sequelize automatically create table?

Automatically creates tables in MySQL database if they don't exist by calling await sequelize.


2 Answers

After digging further into the documentation, I believe I've found the answer.

When creating a many to many relationship sequelize creates get, set and add methods to each model.

From the docs assuming models User and Project with many to many: http://docs.sequelizejs.com/en/latest/docs/associations/#belongs-to-many-associations

This will add methods getUsers, setUsers, addUsers to Project, and getProjects, setProjects and addProject to User.

So in my case I did the following where "city" is a specific City model returned from City.find...

//user.setCities([city]);  models.User.find({ where: {first_name: 'john'} }).on('success', function(user) {   models.City.find({where: {id: 10}}).on('success', function(city){     user.setCities([city]);   });       }); 
like image 116
RickTakes Avatar answered Sep 18 '22 00:09

RickTakes


You can create a new instance of the model used as the join table once both City and User models have been created.

const User = sequelize.define('user') const City = sequelize.define('city') const UserCity = sequelize.define('user_city')  User.belongsToMany(City, { through: UserCity }) City.belongsToMany(User, { through: UserCity })   const user = await User.create() const city = await City.create()  const userCity = await UserCity.create({   userId: user.userId,   cityId: city.cityId, }) 
like image 30
Danny Sullivan Avatar answered Sep 21 '22 00:09

Danny Sullivan