How i can get all links with their user in prisma client?


#1

I’m trying to query all links with the name of the user who posted it.
here is my link type and relation to the user

type Link {
id: ID! @unique
createdAt: DateTime!
description: String!
url: String!
postedBy: User
}

in my resolver i have

allLinks = async (parent,args,ctx) => {
    return await ctx.prisma.links();
}

#2

Hey @ahrbil

you can get all links including the user who posted them using the $fragment API:

prisma.links().$fragment(`
  fragment LinksWithUser on Link {
    id
    createdAt
    description
    url
    postedBy {
      id
      name
    }
  }
`)

However, it seems like you want to use the Prisma client inside your own resolver in which case should implement the type resolvers for User and Link to resolve your relations:

const resolvers = {
  Query: {
    // ...
  },
  Mutation: {
    // ...
  },
  User: {
    links: (parent, args, ctx) => {
      return ctx.prisma.user({id: args.id}).links()
    }
  },
  Link: {
    postedBy: (parent, args, ctx) => {
      return ctx.prisma.link({id: args.id}).postedBy()
    }
  }
}

Find more info here :slight_smile:


#3

thank you so much @nikolas for your response
I have another question about the performance of using the second solution because now I will be making one more request to the database instead if I use fragment the relation will resolve in one request is that right?
thank you again


#4

You don’t need to worry about performance. The Prisma client comes with a built-in dataloader, which means its requests will be batched. The two calls to the Prisma API end up being a single HTTP request :slight_smile: