gpt4 book ai didi

sequelize.js - "has many through" Sequelize 中的关联

转载 作者:行者123 更新时间:2023-12-05 00:52:27 24 4
gpt4 key购买 nike

假设我们有三个模型:

  • 书籍
  • 章节
  • 段落

  • 以下是他们的关联:
  • 图书有很多章节 .
  • 章节有很多段落 .
  • 图书有很多段落 , 通过 章节 .

  • 是否可以与 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在两个 BookParagraph模型喜欢 getParagraphsgetBook为了检索关联元素

    // 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 - "has many through" Sequelize 中的关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42708811/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com