Sequelize(5) 一对多对多

一对一

hasOne

belongsTo

区别: 联系键 添加的地方不一样

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);     // 添加 teamId 到 Player
Coach.hasOne(Team);         //添加 coachId 到 Team

通过 hasOne 方法添加的模型

对新添加模型的 setter 和 getter 会自动以模型名为后缀

此外,也会以 模型名+id 的形式生成外码

可以通过以下代码修改

// Person#getPerson, Person#setPerson

Person.hasOne(Person);


// 增加方法Person#getFather,Person#setFather
// 修改外码为dadId

Person.hasOne(Person, {as: 'Father', foreignKey: 'dad_id'})

一对多

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

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

多对多

使用belongToMany,为两个多对多的模型建立联系

通过创建一个中间模型(联系集)实现

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'})


// 添加一个 project, 并且,设置其状态为 started

user.addProject(project, { status: 'started' })


// 使用 through 可以选择特定属性

User.findAll({
  include: [{
    model: Project,
    through: {
      attributes: ['createdAt', 'startedAt', 'finishedAt'],
      where: {completed: true}
    }
  }]
});

你可能感兴趣的:(Sequelize(5) 一对多对多)