简体   繁体   中英

Get data from secondary table in Prisma2

I have a User table that contains user data. I also have a Relationship table that contains a parent_id and a child_id as well as the incrementing id . Each Parent can have many Children and I am trying to retrieve the array of children using the parent_id . I am currently getting an array, but the array only contains the Relationship table data.

How do I get the data from the User table? I was under the impression that because there is a relationship the following should work, but it doesnt.

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

The relevant code is as follows:
Query:

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

The query below should do it

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

You need to specify the include param explicitly to include the relationship in the output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM