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?
}
});