Prisma data modeling has many and belongs to

1.4k views Asked by At

I have a prisma data model that consists of a root Category and a Subcategory. A Category has many Subcategories and a Subcategory belongs to one Category. My model looks like this:

  type Category {
    id: ID! @unique
    createdAt: DateTime!
    updatedAt: DateTime!
    name: String!
    subCategories: [SubCategory!]! @relation(name: "Subcategories")
  }

  type SubCategory {
    id: ID! @unique
    createdAt: DateTime!
    updatedAt: DateTime!
    name: String!
    category: Category! @relation(name: "ParentCategory")

    cards: [Card!]! @relation(name: "SubCategoryCards") #Category @relation(name: "CardCategory")
  }

Now when i go to create a new subcategory and via

mutation {
    createSubCategory(data:{
        name:"This is a test"
        category:{
            connect:{
                id:"cjp4tyy8z01a6093756xxb04i"
            }
        }
    }){
        id
        category{
            name
            id
        }
    }
}

This appears to work fine. Below I query for the subcategories and their parent Category and I get the results that I expect.

{
    subCategories{
        id
        name
        category{
            id
            name
        }
    }
}

However, when i try to query a category, and get all of it's sub categories I'm getting an empty array:

{
    categories{
        id
        name
        subCategories{
            id
            name
        }
    }
}

How can I query all categories and get their sub categories?

1

There are 1 answers

1
Errorname On BEST ANSWER

As per the documentation, the @relation directive is used to specify both ends of a relation.

Let's take the following datamodel:

type User {
  postsWritten: [Post!]!
  postsLiked: [Post!]!
}

type Post {
  author: User!
  likes: [User!]!
}

Here, we have an ambiguous relation between Post and User. Prisma needs to know which User field (postsWritten? postsLiked?) to link to which Post field (author? likes?)

To resolve this, we use the @relation with a name used in both ends of the relation.

This would make the datamodel look like this:

type User {
  postsWritten: [Post!]! @relation(name: "AuthorPosts")
  postsLiked: [Post!]! @relation(name: "UserLikes")
}

type Post {
  author: User! @relation(name: "AuthorPosts")
  likes: [User!]! @relation(name: "UserLikes")
}

Because we used the same name for the postsWritten and author fields, Prisma is now able to link these two in the database. Same for postsLiked and likes.

In conclusion, the problem with your datamodel is that you used different names in your relation. This confuses Prisma which think those are different relations. Which explains why you can query one way but not another.