I've figured it out. Just in case it's useful to a...
# orm-help
n
I've figured it out. Just in case it's useful to anyone . . .
Copy code
model User {
  id        Int @id @default(autoincrement())
  name      String
  email     String @unique
  games     UserGame[]
  friends   User[] @relation("Friends")
  friendOf  User[] @relation("Friends")
}
Copy code
type User {
    id: Int!
    name: String!
    email: String!
    games: [UserGame]!
    friends: [User]
    friendOf: [User]
  }

  type Query {
    user(email: String): User
    users: [User!]!
  }

  input CreateUserInput {
    name: String!
    email: String!
  }

  input UpdateUserInput {
    name: String
    email: String
  }

  input FriendInput {
    id: Int!
    friendId: Int!
  }

  type Mutation {
    createUser(input: CreateUserInput!): User
    addFriend(input: FriendInput!): User
    removeFriend(input: FriendInput!): User
  }
Copy code
export const user = ({ email }) => {
  return db.user.findUnique({
    where: { email },
    include: { friends: true, friendOf: true },
  })
}

export const users = () => {
  return db.user.findMany({ include: { friends: true, friendOf: true } })
}

export const User = {
  games: (_obj, { root }) =>
    db.user.findUnique({ where: { id: root.id } }).games(),
}

export const addFriend = ({ input }) => {
  return db.$transaction([
    db.user.update({
      where: {
        id: input.id,
      },
      data: {
        friends: {
          connect: {
            id: input.friendId,
          },
        },
      },
    }),
    db.user.update({
      where: {
        id: input.friendId,
      },
      data: {
        friends: {
          connect: {
            id: input.id,
          },
        },
      },
    }),
  ])
}

export const removeFriend = ({ input }) => {
  return db.$transaction([
    db.user.update({
      where: {
        id: input.id,
      },
      data: {
        friends: {
          disconnect: {
            id: input.friendId,
          },
        },
      },
    }),
    db.user.update({
      where: {
        id: input.friendId,
      },
      data: {
        friends: {
          disconnect: {
            id: input.id,
          },
        },
      },
    }),
  ])
}
Copy code
mutation {
  addFriend(input: { id: 4, friendId: 3 }) {
    id
  }
}

mutation {
  removeFriend(input: { id: 4, friendId: 3 }) {
   id 
  }
}

query  {
   users {
    id,
    name,
    email
    friends {
      id
      name
    }
    friendOf {
      id,
      name
    }
  }
}
💯 1
r
@Nick 👋 You can also use long-running transactions in this case as we support this: https://github.com/prisma/prisma/releases/tag/2.29.0