One to one

hasOne

belongsTo

Difference: The place where the contact key is added is different

var Player = this.sequelize.define('player', {/* attributes */}), 
    Coach  = this.sequelize.define('coach', {/* attributes */}), 
    Team  = this.sequelize.define('team', {/* attributes */}),
    Game =  this.sequelize.define('game', {/* attributes */}); Player.belongsTo(Team); // Add teamId to Player coach.hasone (Team); // Add coachId to TeamCopy the code

Models added through the hasOne method

Setters and getters for newly added models are automatically suffixed with the model name

In addition, a foreign code is generated in the form of model name + ID

This can be modified with the following code

// Person#getPerson, Person#setPersonPerson.hasOne(Person); // Add method Person#getFather,Person#setFatherDadId person. hasOne(Person, {as:'Father', foreignKey: 'dad_id'})
Copy the code

More than a pair of

var User = sequelize.define('user'{/ *... */}) var Project = sequelize.define('project'{/ *... */}) // Project#getWorkers , Project#setWorkers

Project.hasMany(User, {as: 'Workers'})
Copy the code

Many to many

Use belongToMany to make a connection between two many-to-many models

This is done by creating an intermediate model (contact set)

User = sequelize.define('user', {})
Project = sequelize.define('project', {})
UserProjects = sequelize.define('userProjects', {
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    status: DataTypes.STRING
})
 
User.belongsToMany(Project, {  as: 'Tasks', through: UserProjects, foreignKey: 'userId' })
Project.belongsToMany(User, {  as: 'Workers',through: UserProjects ,foreignKey: 'projectId'}) // Add a project and set its state to started user.addProject(project, {status:'started'}) user.findall ({include: [{model: Project, through: {attributes: ['createdAt'.'startedAt'.'finishedAt'].where: {completed: true}}}]Copy the code