3
比方说,我们有三种型号:“经历了许多” 协会Sequelize
- 书
- 章
- 段落
这里是他们的协会:
- Books ha很多章节。
- 章节有很多段落。
- Books有很多段落,通过章节。
是否可以定义与Sequelize有'很多,通过'的关系?如果是这样,怎么样?
这里有图书,章,和段落非常基本的模型:
// Book model
const Book = sequelize.define('Book', {
id: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true
},
title: {
type: DataTypes.STRING
}
}, {
classMethods: {
associate: (models) => {
Book.hasMany(models.Chapter, {
foreignKey: 'bookId',
as: 'chapters'
});
}
// How can you add an association for a book having many paragraphs, through chapters?
}
});
// Chapter model
const Chapter = sequelize.define('Chapter', {
id: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true
},
title: {
type: DataTypes.STRING
}
}, {
classMethods: {
associate: (models) => {
Chapter.hasMany(models.Paragraph, {
foreignKey: 'chapterId',
as: 'paragraphs'
});
Chapter.belongsTo(models.Book, {
foreignKey: 'bookId'
});
}
}
});
// Paragraph Model
const Paragraph = sequelize.define('Paragraph', {
id: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true
},
content: {
type: DataTypes.TEXT
}
}, {
classMethods: {
associate: (models) => {
Paragraph.belongsTo(models.Chapter, {
foreignKey: 'chapterId'
});
}
// How can you add an association for paragraphs belonging to a book "through" chapters?
}
});