2017-03-10 62 views
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? 
    } 
}); 

回答

3

不幸的是没有这种可能性。你可以做的是为了获取相关的元素

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

以上方法将返回其章属于指定书所有段落创建两个BookParagraph模型像getParagraphsgetBook一些instanceMethods。你可以在Paragraph模型中做getBook

另一方面,为了检索所有章节及其段落的书籍,您只需执行findAll嵌套include(笑话提醒)。