2017-03-10 79 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(笑話提醒)。