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

I create a simple database with node, express and securitize. I created my models, and sequelize created tables in my database.

I have User and City models with many relationships. Sequelize creates the Users, Cities tables, and the CitiesUsers: connection table with UserId and CityId.

My question is when I create a new user, how do I update this connection table? The CityId property is ignored during creation.

//Models use //City.hasMany(User); //User.hasMany(City); var user = User.build({ first_name: 'John', last_name: 'Doe', CityId: 5 }); user.save(); 
+10
source share
4 answers

After a deeper study of the documentation, I think I found the answer.

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

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

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

So in my case, I did the following, where the "city" is a specific model of the city 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]); }); }); 
+8
source

You can create a new instance of the model used as the connection table after the City and User models are 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 }) Promise.all([User.create(), City.create()]) .then(([user, city]) => UserCity.create({userId: user.id, cityId: city.id})) 
+5
source

From d3 doc:

 // Either by adding a property with the name of the join table model to the object, before creating the association project.UserProjects = { status: 'active' } u.addProject(project) // Or by providing a second argument when adding the association, containing the data that should go in the join table u.addProject(project, { status: 'active' }) // When associating multiple objects, you can combine the two options above. In this case the second argument // will be treated as a defaults object, that will be used if no data is provided project1.UserProjects = { status: 'inactive' } u.setProjects([project1, project2], { status: 'active' }) // The code above will record inactive for project one, and active for project two in the join table 
+1
source

Just to add to the many excellent answers in this thread, I find that, as a rule, when one entity refers to another, I want to create a reference entity if (and only if) it does not already exist. For this, I like to use findOrCreate() .

So, imagine that you are storing articles, and each article can have any number of tags. What you usually want to do is:

  1. Go through all the tags you need and check if they exist. Create them if they do not already exist.
  2. Once all the tags have been found or created, create your article.
  3. Once your article is created, link it to the tags you searched for (or created) in step 1.

For me it looks like this:

 const { article, tags } = model.import("./model/article"); let tagging = [ tags.findOrCreate({where: {title: "big"}}), tags.findOrCreate({where: {title: "small"}}), tags.findOrCreate({where: {title: "medium"}}), tags.findOrCreate({where: {title: "xsmall"}}) ]; Promise.all(tagging).then((articleTags)=> { article.create({ title: "Foo", body: "Bar" }).then((articleInstance) => { articleInstance.setTags(articleTags.map((articleTag) => articleTag[0])); }) }) 
0
source

Source: https://habr.com/ru/post/1214511/


All Articles