I have the following schema:
model Post {
id Int @id @default(autoincrement())
slug String @unique
title String
markdown String
postImageUrl String
ogLocale String @default("en_US")
tags TagsOnPosts[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Cascade, onUpdate: Cascade)
userId String
}
model Tag {
id Int @id @default(autoincrement())
name String
posts TagsOnPosts[]
}
model TagsOnPosts {
post Post @relation(fields: [postId], references: [id])
postId Int
tag Tag @relation(fields: [tagId], references: [id])
tagId Int
assignedAt DateTime @default(now())
assignedBy String
@@id([postId, tagId])
}
And the following code in order to insert a new post:
export async function createPost(
post: Pick<Post, "slug" | "title" | "markdown" | "postImageUrl">,
tags: string[],
userId: string
) {
const tagsCreate = tags.map((tag) => {
return {
tag: {
connectOrCreate: {
where: { name: tag },
create: { name: tag, id: null },
}
},
assignedBy: userId
}
});
return prisma.post.create({
data: {
slug: post.slug,
title: post.title,
markdown: post.markdown,
postImageUrl: post.postImageUrl,
userId: userId, // provide the userId here
tags: {
create: tagsCreate
}
}
});
}
Posting the rest as a comment..