多对多关系棱镜
Posted
技术标签:
【中文标题】多对多关系棱镜【英文标题】:Many to many relationship prisma 【发布时间】:2022-01-19 22:24:20 【问题描述】:我有一个带有 Typescript mysql 的快速服务器,也使用 Prisma Js 进行 ORM。这些是我的架构:
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])
首先我创建一个新类别然后我将创建一个新帖子但我无法弄清楚这个问题有人可以帮助我吗?这也是我的要求:
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 );
;
但是当我尝试创建新帖子时,我在 CategoriesOnPosts 模型中看不到任何类别
【问题讨论】:
【参考方案1】:为了简化示例,我已从您的架构中删除了用户
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])
执行迁移后,我执行了以下代码:
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()
一切正常,给你一张带有结果的图片
【讨论】:
我真的很感谢你!这是很好的解释 很高兴! :),请给我的答案打分! :)以上是关于多对多关系棱镜的主要内容,如果未能解决你的问题,请参考以下文章