Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

376
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda