只有 return 指定了来自 sequelize 连接模型的关联模型

Only return specified associated model from sequelize junction model

我正在尝试正确使用 sequelize 查询来使用 graphql + apollo。

这是我的 Pool gql 架构:

  type Pool {
    id: ID!
    name: String!
    createdBy: User
    members: [User]
  }

这里是池模型关联

  Pool.associate = models => {
    Pool.belongsToMany(models.User, {
      onDelete: 'CASCADE',
      through: models.UserPool,
      foreignKey: models.UserPool.poolId,
    })
  }

User也是如此 架构:

  type User {
    id: ID!
    username: String!
    email: String!
    role: String
  }

模型关联

  User.associate = models => {
    User.belongsToMany(models.Pool, {
      onDelete: 'CASCADE',
      through: models.UserPool,
      foreignKey: 'userId',
    })
  }

所以这两个模型通过一个名为 UserPool 仅存储 UserPool 的 pks。

在我的 ./resolvers/pool.js 中,我正在为 Pool 定义我的 gql 模型解析器。 这就是我的问题所在。 在下面的 members 字段中,我只想 return 一个 User 的数组 对象,我可以通过 UserPool

访问
  Pool: {
    createdBy: async (pool, _, { models }) => {
      // this sequelize built-in works and returns the createdBy User model
      const user = await pool.getUser()
      return user
    },
    members: async (pool, _, { models }) => {
      let users = []

      const poolUsers = await models.UserPool.findAll({
        where: { poolId: pool.id },
      })


      // *** below is what I want to do -- use the in-built ***
      // *** sequelize query methods you get with the n:m assoc ***

      const users = await poolUsers.getUsers()

      // However, each time this throws an error: 
      // getUsers() is not a function....

      return users
    },
  },

为了说明我的基础,这是我的 UserPool 模型关联 def:

  UserPool.associate = models => {
    UserPool.belongsTo(models.User, {
      onDelete: 'CASCADE',
      foreignKey: 'userId',
    })
    UserPool.belongsTo(models.Pool, {
      onDelete: 'CASCADE',
      foreignKey: 'poolId',
    })
  }

我尝试在 Sequelize 中使用自动方法,但它们似乎不起作用。

你可以这样做:

models.User.findAll({
        include: [{
            model: models.UserPool,
            where: { poolId: pool.id },
            required: true
        }]

poolUsers 是 UserPool 对象的数组,因此它没有 getUsers 方法。您可以映射每个 UserPool 并获取用户,但这会导致不必要地大量调用您的数据库。

您已经在 PoolUser 之间创建了关联。所以你可以做

members: async (pool) => {
  return pool.getUsers()      
}