Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

370
Views
Many to many relationship prisma

I have an express server with Typescript Mysql also using Prisma Js for ORM. These are my schemas:

model Post {
  id          Int                 @id @default(autoincrement())
  title       String              @db.VarChar(35)
  description String              @db.VarChar(250)
  category    CategoriesOnPosts[]
  author      User                @relation(fields: [userId], references: [id])
  userId      String
  createdAt   DateTime            @default(now())
  updatedAt   DateTime            @updatedAt
}

model Category {
 id    Int                 @id @default(autoincrement())
 name  String              @unique @db.VarChar(18)
 about String              @db.VarChar(60)
 posts CategoriesOnPosts[]
}

model CategoriesOnPosts {
 post       Post     @relation(fields: [postId], references: [id])
postId     Int
category   Category @relation(fields: [categoryId], references: [id])
categoryId Int

 @@id([postId, categoryId])
}

first I create a new category then I will create a new post but I can't figure out this problem can any one help me ? also here is my requests:

export const createCategory = async (req: Request, res: Response) => {
 try {
   const { name, about } = req.body;
   if (!name || !about) return res.status(400).json({ error: 'Please fill all inputs!' });
   const existCategory = await prisma.category.findUnique({ where: { name } });
   if (existCategory) return res.status(400).json({ error: 'This category already exists!' });
   const category = await prisma.category.create({
     data: {
        name,
        about,
     },
  });
  res.status(201).json(category);
 } catch (error) {
  res.status(500).json({ error: error.message });
 }
};

but when I try to create a new post I can't see any category in CategoriesOnPosts model

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I have removed User from your schema in order to simplify the example

datasource mysql {
  provider = "mysql"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

model Post {
  id          Int                 @id @default(autoincrement())
  title       String
  description String
  category    CategoriesOnPosts[]
  createdAt   DateTime            @default(now())
  updatedAt   DateTime            @updatedAt
}

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

model CategoriesOnPosts {
  post       Post     @relation(fields: [postId], references: [id])
  postId     Int
  category   Category @relation(fields: [categoryId], references: [id])
  categoryId Int

  @@id([postId, categoryId])
}

After I have executed the migration, I have executed the following code:

const { PrismaClient } = require('@prisma/client')
const prisma = new PrismaClient()

const loadData = async () => {
  const category = await prisma.category.create({
    data: {
      name: 'Category 1',
      about: 'Description 1',
    },
  });

  console.log(category);

  const post = await prisma.post.create({
    data: {
      title: 'Post 1',
      description: 'Description 1',
      category: {
        create: {
          category: {
            connect: {
              id: category.id
            }
          }
        }
      }
    },
  });

  console.log(post);
};

loadData()

And all works properly, here you go a image with the result

result

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!