javascript - 如何消除 Sequelize 中相同模型之间的多个关联之间的歧义

标签 javascript join sequelize.js

我有三个模型 - BookUserInstitution - 它们相互关联,如下所示:

  • 书籍通过 Book_Institution 连接表与机构关联(多对多关系)

    Book.belongsToMany(models.Institution, { through: 'Book_Institution' })
    

    Institution.belongsToMany(models.Book, { through: 'Book_Institution' })
    
  • 用户可以通过两种方式与机构关联:作为读者或作者。这是通过两个连接表完成的:Author_InstitutionReader_Institution:

    Institution.belongsToMany(models.User, { through: 'Author_Institution' })
    Institution.belongsToMany(models.User, { through: 'Reader_Institution' })
    

    User.belongsToMany(models.Institution, { through: 'Author_Institution' })
    User.belongsToMany(models.Institution, { through: 'Reader_Institution' })
    

    (为了简洁起见,每次都省略 foreignKey。)

我想查询 Book 模型以查找属于某个作者的所有书籍。 Sequelize 提供 include 选项来轻松连接两个关联的表。我遇到的问题是,使用如下所示的 include 默认为 Reader_Institution 关联。我如何指定应使用哪个关联?

getBooks: (obj, args, context) => {
  const { user } = context

  return Book.findAll({
    attributes: ['id', 'path'],
    include: [{
      include: [{
        attributes: ['id'],
        model: User,
        where: { id: user }
      }],
      model: Institution,
      required: true // inner join
    }]
  })
}

预先感谢您的帮助。

最佳答案

我使用 as ,它允许您通过该别名引用关系。

Institution.belongsToMany(models.User, { 
    through: 'Author_Institution', // many-to-many relationship table name
    as: 'AuthorInstitution' // alias
})

以这种方式设置模型后,您可以使用 as 来指定查询时要包含的关系。

getBooks: (obj, args, context) => {
  const { user } = context

  return Book.findAll({
    attributes: ['id', 'path'],
    include: [{
      include: [{
        attributes: ['id'],
        model: User,
        where: { id: user },
        as: 'AuthorInstitution'
      }],
      model: Institution,
      required: true // inner join
    }]
  })
}

此外,通过这种方法,您可以通过 as 引用关系数据,因此您可以执行 book.AuthorInstitution ,它将是那个对象。

关于javascript - 如何消除 Sequelize 中相同模型之间的多个关联之间的歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48647236/

相关文章:

javascript - 使用 ES6 扩展运算符 react props 语法

javascript - 视口(viewport) iframe

mysql - LEFT JOIN 后填充缺失值的最佳方法?

node.js - Sequelize增量函数返回错误

javascript - 将对象数组转换为具有数组值的对象

python - 在 sqlalchemy 中外部连接两个表时按问题排序

jpa - JPQL 查询中的 @OrderColumn

node.js - 通过 Sequelize 使用多个数据存储连接

javascript - 在 sequelize 中,如何定义 X 属于 A 或 B 的关系?

javascript - 使用socket.io更新express实时 View