一對一
hasOne
belongsTo
區(qū)別:
聯(lián)系鍵
添加的地方不一樣
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,為兩個多對多的模型建立聯(lián)系
通過創(chuàng)建一個中間模型
(聯(lián)系集)
實(shí)現(xiàn)
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, 并且,設(shè)置其狀態(tài)為 started
user.addProject(project, { status: 'started' })
// 使用 through 可以選擇特定屬性
User.findAll({
include: [{
model: Project,
through: {
attributes: ['createdAt', 'startedAt', 'finishedAt'],
where: {completed: true}
}
}]
});