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();
Automatically creates tables in MySQL database if they don't exist by calling await sequelize.
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]); }); });
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, })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With