Prisma 1 Forum

I want to make a relation for these two types

I’m creating an app that needs users and groups.
Users can create groups, users can be apart of multiple groups.
Here is how my schema looks:

   type User {
    	 id: ID! @id
    	 first_Name: String!
    	 last_Name: String!
    	 email: String! @unique
    	 groups: [Group] @relation(name: "GroupsByUser")
    	 createdAt: DateTime!
    }


type Group {
  id: ID! @id
  title: String
  author: User! @relation(name: "GroupsByUser")
  members: [User] @relation(name: "GroupsByUser")
  draw_amount: Int!
  createdAt: DateTime!
}

I keep receiving this issue when I try to deploy. CAN’T figure out how to fix it. Any help is appreciated.

Group
:heavy_multiplication_x: A relation directive cannot appear more than twice. Relation name: ‘GroupsByUser’
:heavy_multiplication_x: A relation directive cannot appear more than twice. Relation name: ‘GroupsByUser’

SideNote: Do I need to include createdAt on both types or are they created automatically?

In your example you’re linking the user type with the group type. The user can be part of multiple groups, therefore it has the groups array field. And a group can have multiple members, therefore the members array field. This is all correct. Where it goes wrong is the author having the same relation. A relation between two types can only be on a single field per type. Prisma would not know what to return if you’d query for groups on the user if it’s linked to 2 fields on the Group type. Does Prisma have to return the members, or the author? Like I mentioned, there is a clear relation between the user having the group field they’re a member of and the group type with all the members. The author field needs a relation by itself to solve the problem. There can only be one author. The user can be author of multiple groups. So I would do it like this:

   type User {
	 id: ID! @id
	 first_Name: String!
	 last_Name: String!
	 email: String! @unique
     createdGroups: [Group] @relation(name: "CreatedGroupsByUser")
	 groups: [Group] @relation(name: "GroupsByUser")
	 createdAt: DateTime!
}

type Group {
  id: ID! @id
  title: String
  author: User! @relation(name: "CreatedGroupsByUser")
  members: [User] @relation(name: "GroupsByUser")
  draw_amount: Int!
  createdAt: DateTime!
}

The naming is up to you. Hope it helped out.

1 Like

Thank you, your explanation made sense and your example worked!

This topic was automatically closed 45 days after the last reply. New replies are no longer allowed.