“有很多通过"Sequelize 中的关联 [英] "has many through" association in Sequelize
问题描述
假设我们有三个模型:
- 书籍
- 章节
- 段落
以下是它们的关联:
- 书籍有很多章节.
- 章节有很多段落.
- 书籍有很多段落,通过章节.
- Books have many chapters.
- Chapters have many paragraphs.
- Books have many paragraphs, through chapters.
是否可以定义与 Sequelize 的有很多,通过"关系?如果是这样,如何?
以下是书籍、章节和段落的非常基本的模型:
Here are very basic models for Book, Chapter, and Paragraph:
// 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?
}
});
推荐答案
遗憾的是没有这种可能性.您可以做的是在 Book
和 Paragraph
模型上创建一些 instanceMethods
,例如 getParagraphs
和 getBook
以检索关联元素
Unfortunately there is no such a possibility. What you can do is to create some instanceMethods
on both Book
and Paragraph
model like getParagraphs
and getBook
in order to retrieve associated elements
// in Book model
instanceMethods: {
getParagraphs: function(options){
options.include = [
{
model: sequelize.models.Chapter,
attributes: [],
where: {
bookId: this.get('id')
}
}
];
return sequelize.models.Paragraph.findAll(options);
}
}
Above 方法将返回所有章节属于指定书籍的段落.您可以对 Paragraph
模型中的 getBook
执行相反的操作.
Above method would return all paragraphs whose chapter belongs to specified book. And you could do the reverse for getBook
in the Paragraph
model.
另一方面,为了检索书籍的所有章节及其段落,您只需使用嵌套的 include
执行 findAll
(开玩笑地提醒一下).
On the other hand, in order to retrieve book with all it's chapters and their paragraphs, you would simply perform findAll
with nested include
(jest reminding about that).
这篇关于“有很多通过"Sequelize 中的关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!