假设我们有三个模型:
以下是他们的关联:
是否可以定义与 Sequelize 的“有很多,通过”关系?如果是这样,如何?
以下是 Book、Chapter 和 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?
}
});
最佳答案
不幸的是,没有这种可能性。您可以做的是在 instanceMethods
和 Book
模型(如 Paragraph
和 getParagraphs
)上创建一些 getBook
以检索关联元素
// 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);
}
}
上述方法将返回其章节属于指定书籍的所有段落。您可以对
getBook
模型中的 Paragraph
进行相反的操作。另一方面,为了检索包含所有章节及其段落的书籍,您只需使用嵌套的
findAll
执行 include
(开玩笑地提醒一下)。关于sequelize.js - Sequelize 中的 "has many through"关联,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42708811/