Javascript 如何在Sequelize中消除同一模型之间的多个关联之间的歧义

Javascript 如何在Sequelize中消除同一模型之间的多个关联之间的歧义,javascript,join,sequelize.js,Javascript,Join,Sequelize.js,我有三个模型——书籍、用户和机构——它们相互关联,如下所示: 图书通过图书与机构联接表多对多关系与机构关联 Book.belongsToMany(models.Institution, { through: 'Book_Institution' }) 及 用户可以通过两种方式与机构关联:作为读者或作者。这是通过两个联接表完成的:Author\u Institution和Reader\u Institution: 及 为了简洁起见,每次都省略了foreignKey 我想查询图书模型以查找属于作者

我有三个模型——书籍、用户和机构——它们相互关联,如下所示:

图书通过图书与机构联接表多对多关系与机构关联

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

用户可以通过两种方式与机构关联:作为读者或作者。这是通过两个联接表完成的:Author\u Institution和Reader\u Institution:

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

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

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 to指定查询时要包含的关系

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.authoritionstitution,它将是该对象的值。

这不会导致1对多关系而不是多对多关系吗?不。我没有改变你的结构,你仍然会拥有每个物体的归属感,我只是把直通改为as。我冒昧地猜测,您可以退出直通,只添加一个,好像您对此更满意,但as本质上只是为关系创建了一个别名。SequelizeAsociationError:BelongTomany必须提供直通选项,无论是字符串还是模型,在关联定义中包含as都不会使其在include中可用。用户使用别名关联到机构。您包含了一个别名测试,但它与您的关联中定义的别名不匹配。我找到了一些关于through选项的文档。它是关系表,是必需的。我现在还不能测试这个,但是你有没有试着在那里留下一个直通,只是把as添加到你的关联中?确保已将as添加到关联和包含中。谢谢!使用as的别名策略似乎有效。我很困惑,因为用户的别名必须设置为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
    }]
  })
}
Institution.belongsToMany(models.User, { 
    through: 'Author_Institution', // many-to-many relationship table name
    as: 'AuthorInstitution' // alias
})
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
    }]
  })
}