首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在后缀中如何消除相同模型之间的多个关联之间的歧义

在后缀中如何消除相同模型之间的多个关联之间的歧义
EN

Stack Overflow用户
提问于 2018-02-06 16:08:58
回答 1查看 2.4K关注 0票数 0

我有三种模型-- BookUserInstitution --它们相互关联如下:

  • 书籍通过Book_Institution连接表(许多与许多关系)与机构相关联。 Book.belongsToMany(models.Institution,{ through:'Book_Institution‘}) 和 Institution.belongsToMany(models.Book,{ through:'Book_Institution‘})
  • 用户可以通过两种方式与机构联系:作为读者或作者。这是通过两个连接表来完成的:Author_InstitutionReader_Institution: Institution.belongsToMany(models.User,{透:'Author_Institution‘}) Institution.belongsToMany(models.User,{透:'Reader_Institution’}) 和 User.belongsToMany(models.Institution,{透:'Author_Institution‘}) User.belongsToMany(models.Institution,{透:'Reader_Institution’}) (为了简洁起见,每次都省略foreignKey。)

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

代码语言:javascript
复制
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
    }]
  })
}

提前谢谢你的帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-06 16:27:35

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

代码语言:javascript
复制
Institution.belongsToMany(models.User, { 
    through: 'Author_Institution', // many-to-many relationship table name
    as: 'AuthorInstitution' // alias
})

通过这样设置模型,您可以使用as来指定查询时要包含的关系。

代码语言:javascript
复制
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,它将是该对象的值。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48647236

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档