提问者:小点点

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


我有三个模型-BookUser机构-它们彼此关联如下:

>

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

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

用户可以通过两种方式与机构关联:作为读者或作者。这是通过两个联接表完成的:Author\u InstitutionReader\u 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

我想查询图书模型以查找属于作者的所有图书。Sequelize提供了include选项,可以轻松地联接两个关联的表。我遇到的问题是,使用如下所示的include默认为Reader\u 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
    }]
  })
}

提前感谢你的帮助。


共1个答案

匿名用户

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

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
    }]
  })
}

此外,使用这种方法,它允许您通过作为引用关系数据,因此您可以编写书。它将是该对象的值。