Theo's Typesafe CultTTC
Theo's Typesafe Cult4y ago
32 replies
utdev

Prisma trpc schema multiple models

Hi guys I built a basic t3 stack app, and right now I am stuck. I am trying to create an additional model while creating another one.
This is how my schema looks like:
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model Movie {
  id        String   @id @default(cuid())
  text      String
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  answer    Answer?  @relation(fields: [answerId], references: [id])
  answerId  String?
}

model Answer {
  id        String   @id @default(cuid())
  text      String
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  Movie     Movie[]
}


And this is how I try to create the model
import { z } from "zod";

import { router, publicProcedure } from "../trpc";

export const movieRouter = router({
    getAll: publicProcedure.query(({ ctx }) => {
        return ctx.prisma.movie.findMany();
    }),

    create: publicProcedure.input(z.object({
        text: z.string(),
        answer: z.string(),
    })).mutation(({ ctx, input }) => {

        const answer = ctx.prisma.answer.create({
            data: {
                text: input.text,
            }
        });

        return ctx.prisma.movie.create({
            data: {
                text: input.text,
                answer: {
                    connect: {
                        id: answer.id,
                    }
                },
                // Connect the new Movie to the existing Answer using the 'movies' relation field
                movies: {
                    connect: {
                        id: answer.id,
                    }
                }
            }
        });
    }),
});
Was this page helpful?