paljs / prisma-tools

Prisma tools to help you generate CRUD system for GraphQL servers
https://paljs.com
MIT License
680 stars 55 forks source link

Many-to-many relations generate type not is origin model #250

Open reaink opened 2 years ago

reaink commented 2 years ago

doc: https://www.prisma.io/docs/concepts/components/prisma-schema/relations/many-to-many-relations

schema.prisma

model Post {
  id         Int                 @id @default(autoincrement())
  title      String
  categories CategoriesOnPosts[]
}

model Category {
  id    Int                 @id @default(autoincrement())
  name  String
  posts CategoriesOnPosts[]
}

model CategoriesOnPosts {
  post       Post     @relation(fields: [postId], references: [id])
  postId     Int // relation scalar field (used in the `@relation` attribute above)
  category   Category @relation(fields: [categoryId], references: [id])
  categoryId Int // relation scalar field (used in the `@relation` attribute above)
  assignedAt DateTime @default(now())
  assignedBy String

  @@id([postId, categoryId])
}

post type

import { objectType } from 'nexus'

export const Post = objectType({
  nonNullDefaults: {
    output: true,
    input: false,
  },
  name: 'Post',
  definition(t) {
    t.int('id')
    t.string('title')
    t.list.field('categories', {
      type: 'CategoriesOnPosts',   // this is Category but it is CategoriesOnPosts
      args: {
        where: 'CategoriesOnPostsWhereInput',
        orderBy:
          'CategoriesOnPostsOrderByWithRelationAndSearchRelevanceInput',
        cursor: 'CategoriesOnPostsWhereUniqueInput',
        take: 'Int',
        skip: 'Int',
        distinct: 'CategoriesOnPostsScalarFieldEnum',
      },
      resolve(root: any) {
        return root.categories
      },
    })
  },
})