【问题标题】:Get data from secondary table in Prisma2从 Prisma2 中的辅助表中获取数据
【发布时间】:2020-09-13 01:00:29
【问题描述】:

我有一个包含用户数据的User 表。我还有一个Relationship 表,其中包含parent_idchild_id 以及递增的id。每个父母可以有很多孩子,我正在尝试使用parent_id 检索孩子的数组。我目前正在获取一个数组,但该数组仅包含 Relationship 表数据。

如何从User 表中获取数据?我的印象是,由于存在关系,因此以下应该起作用,但它不起作用。

query {
  getChildren {
    user{
      id
      name
      email      
    }
  }
}

相关代码如下:
查询:

export const getChildren = queryField('getChildren', {
  type: 'User',
  list: true,
  resolve: async (_parent, {}, ctx) => {
    const userId = getUserId(ctx);
    if (!userId) {
      // TODO -think I might need to throw an error here
      return;
    }
    const children = await ctx.prisma.relationship.findMany({
      where: {
        parent_id: userId,
      },
    });
    return children;
  },
});

schema.prisma:

model Relationship {
  child_id            Int
  id                  Int  @default(autoincrement()) @id
  parent_id           Int
  child               User @relation("Relationship_child_idToUser", fields: [child_id], references: [id])
  parent              User @relation("Relationship_parent_idToUser", fields: [parent_id], references: [id])
}

model User {
  created_at          DateTime       @default(now())
  email               String?        @unique
  id                  Int            @default(autoincrement()) @id
  ischild             Boolean        @default(false)
  name                String?
  password            String
  children            Relationship[] @relation("Relationship_child_idToUser")
  parents             Relationship[] @relation("Relationship_parent_idToUser")
}

【问题讨论】:

    标签: graphql nexus prisma nexus-prisma


    【解决方案1】:

    下面的查询应该可以做到

      prisma.relationship.findMany({
        where: {
          parent_id: user_id,
        },
        include: {
          child: true,
        },
      })
    

    您需要明确指定include 参数以将关系包含在输出中。

    【讨论】:

    • 当我添加包含时,我仍然得到相同的结果。虽然 linter 没有问题,所以我们走在正确的轨道上
    • 我正在获取数据伙伴。这是使用的查询:const data = await prisma.relationship.findMany({ where: { parent_id: 1, }, include: { child: true, }, }) 这是响应:[ { child_id: 2, id: 1, parent_id: 1, child: { created_at: 2020-05-26T15:33:13.171Z, email: null, id: 2, ischild: true, name: 'child', password: 'child' } } ] 您是否正确添加了关系?
    • 这是我使用query { getChildren { id name } }的查询与您的相似吗?
    • 我检查了数据库并且表都链接正确
    • 我刚刚检查过,prisma 'findMany` 查询返回了正确的值,但这些值没有显示在 Playground 中。任何想法为什么会这样?
    猜你喜欢
    • 1970-01-01
    • 2012-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多