Linking many-to-many relationships + DB indexing


#1

Hello Prisma community,

I am fairly new to Prisma and had a couple of questions regarding representing many-to-many relationships in the datamodel as well as database indexing. I have the following datamodel for an app where an User can have followers as well as follow other Users and I need to represent each Following as its own type as each following record has a boolean blocked field denoting its status. Note that following someone is not mutual (unlike friendship), hence the unidirectional nature of each entry on the Following relation. Here’s what I have as a datamodel:

type User {
  id: ID! @id
  username: String! @unique
  email: String! @unique
  phoneNum: String @unique
  firstName: String!
  lastName: String!
  password: String!
  followers: [User!]! @relation(name: "UserOnSelf")
  following: [User!]! @relation(name: "UserOnSelf")
  createdAt: DateTime! @createdAt
}

type Following {
  id: ID! @id
  follower: User! @relation(name: "Followers")
  followed: User! @relation(name: "Following")
  blocked: Boolean! @default(value: false)
  createdAt: DateTime! @createdAt
}

In the GraphQL playground, when I query an User object and request a followers and/or a following field, I always get an empty array although I have seeded the DB with entries in the Following table connected to User objects. I think I might have incorrectly specified the @relation directive but I’m not entirely sure how to properly represent this relationship in my datamodel.

If I remove the @relation directives on the follower or followed fields on the Following relation, or either of followers or following on the User relation I get an error when running prisma deploy with a message saying fields must specify a @relation directive: @relation(name: "MyRelation")

Here’s a list of my package.json dependencies:

  "dependencies": {
    "apollo-server-express": "^2.9.3",
    "bcrypt": "^3.0.6",
    "express": "^4.17.1",
    "graphql": "^14.5.4",
    "helmet": "^3.21.0",
    "morgan": "^1.9.1",
    "nexus": "^0.11.7",
    "nexus-prisma": "^0.3.8",
    "prisma-client-lib": "^1.34.8"
  },
  "devDependencies": {
    "@types/bcrypt": "^3.0.0",
    "@types/express": "^4.17.1",
    "@types/graphql": "^14.5.0",
    "@types/helmet": "0.0.44",
    "@types/morgan": "^1.7.37",
    "@types/node": "^12.7.4",
    "@types/ws": "^6.0.3",
    "nodemon": "^1.19.2",
    "ts-node": "^8.3.0",
    "ts-node-dev": "^1.0.0-pre.42",
    "typescript": "^3.4.5"
  }

PS: I am running node version v12.3.1 and npm v6.11.3.

Furthermore, I had another question on database indexing. I was wondering if there was a feature that the Prisma ORM exposes to create indexes on the database itself. If not, then what is the most efficient way to do it? I was thinking of doing it manually by connecting to the DB itself and running a SQL script but I thought there might be a more efficient way of doing things.