如何在prisma查询中创建嵌套连接?

时间:2019-01-24 22:04:38

标签: graphql prisma

我在使pyramida / graphql-yoga客户端正常工作时遇到问题。

我正在尝试创建变异查询,该变异查询在两个节点(GameUser)之间创建连接,但是变异行为并不像我期望的那样。

这是我正在使用的系统:

node --version
v11.6.0

package.json

{
  "dependencies": {
    "graphql-yoga": "^1.17.0",
    "prisma-client-lib": "^1.25.3"
  },
  ...
}

docker-compose.yml

version: '3'
services:
  prisma:
    image: prismagraphql/prisma:1.25
    restart: always
    ports:
    - "4466:4466"
    environment:
      PRISMA_CONFIG: |
        port: 4466
        databases:
          default:
            connector: postgres
            host: postgres
            port: 5432
            user: prisma
            password: prisma
            migrations: true
  postgres:
    image: postgres:10.5
    restart: always
    environment:
      POSTGRES_USER: prisma
      POSTGRES_PASSWORD: prisma
    volumes:
      - postgres:/var/lib/postgresql/data
volumes:
  postgres:

这是datamodel.prisma文件:

type Game {
  id: ID! @unique
  createdAt: DateTime!
  updatedAt: DateTime!
  board: String
  playerOne: User
}

type User {
  id: ID! @unique
  createdAt: DateTime!
  wins: Int
}

这是我发送的变异:

mutation {
  createGame(userId: "cjraz4ogb000s0894lbrugksi") {
    id
    board
    playerOne {
      id
    }
  }
}

以下是解析器:

async function createGame(parent, args, context, info) {
  const game = await context.prisma.createGame({
    playerOne: { connect: { id: args.userId } },
    board: "[[]]"
  })
  return game
}

正如您在响应中看到的那样,解析器创建了一个Game对象,但没有与此游戏相关联的用户。下面显示的是GraphQL游乐场突变的响应:

{
  "data": {
    "createGame": {
      "id": "cjraz8iwr001e08940ok9luki",
      "board": "[[]]",
      "playerOne": null
    }
  }
}

我期望的响应如下所示:

{
  "data": {
    "createGame": {
      "id": "cjraz8iwr001e08940ok9luki",
      "board": "[[]]",
      "playerOne": {
        id: "cjraz8iwr001e08940ok9luki" <- id from above
      }
    }
  }
}

解决方案

就像@Errorname提到的那样,我需要实现playerOne关系的resolver函数。在下面添加代码行即可解决此问题。

function playerOne(parent, args, context, info) {
  return context.prisma.game({ id: parent.id }).playerOne()
}

1 个答案:

答案 0 :(得分:1)

由于使用的是prisma-client,因此必须为连接(Documentation)编写解析器:

Game: {
  playerOne: (root, args, ctx) => ctx.prisma.game({id: root.id}).playerOne()
}