"Explicit" 1-1 Self-relations in Prisma - javascript

Say I have a model called Room and another called Path.
Each Room is connected to each other by Paths. The Path is not one-way, you can go from one Room to another Room via a Path, and vice versa through the same Path.
Each Room and Path must have a name attribute. This is to identify Rooms and Paths as different from each other, like how two Paths can connect to the same two rooms (eg. a path that goes through the window and another that goes through a door)
How would I model this in Prisma in a PostgreSQL database?
Best attempt so far (but ultimately fails):
model Room {
id Int #id #default(autoincrement())
name String
connected_paths Path[] // ???
}
model Path {
id Int #id #default(autoincrement())
name String
location_1 Location // ???
location_2 Location // ???
}

I have run into same issue once, but I was using SQLServier after a lot of research I ended up making something like this:
model Room {
id Int #id #default(autoincrement())
name String
paths RoomPath[]
}
model Path {
id Int #id #default(autoincrement())
name String
rooms RoomPath[]
}
model RoomPath {
id Int #id #default(autoincrement())
Room Room #relation(fields: [roomId], references: [id])
roomId Int
Path Path #relation(fields: [pathId], references: [id])
pathId Int
}

Related

How to soft delete a explicit many to many relation in prisma and what are the best practices in doing so

I want to implement soft delete in explicit many to many relation using prisma. I want to somehow disconnect the link betweeen them and mark both user and all its memories as deleted true.
is it a good approach ? or how to do this in genral
My Prisma Schema looks like this:
model User {
userId String #id #default(uuid())
memories UserMemory[]
deleted Boolean #default(false)
}
model Memory {
memoryId String #id #default(uuid())
users UserMemory[]
deleted Boolean #default(false)
}
model UserMemory {
userId String
user User? #relation(fields: [userId], references: [userId])
memoryId String
memory Memory? #relation(fields: [memoryId], references: [memoryId])
##id([userId, memoryId])

How do i get the GitHub username for signed in user, with GitHub auth

I am using Next Auth and Prisma adaptor but the user information i get is just there email and name, not there actual github username or any other type of info, this is what the prisma schema looks like
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
referentialIntegrity = "prisma"
}
generator client {
provider = "prisma-client-js"
previewFeatures = ["referentialIntegrity"]
}
model Account {
id String #id #default(cuid())
userId String
type String
provider String
providerAccountId String
refresh_token String? #db.Text
access_token String? #db.Text
expires_at Int?
token_type String?
scope String?
id_token String? #db.Text
session_state String?
user User #relation(fields: [userId], references: [id], onDelete: Cascade)
##unique([provider, providerAccountId])
}
model Session {
id String #id #default(cuid())
sessionToken String #unique
userId String
expires DateTime
user User #relation(fields: [userId], references: [id], onDelete: Cascade)
}
model User {
id String #id #default(cuid())
name String?
email String? #unique
emailVerified DateTime?
image String?
accounts Account[]
sessions Session[]
}
model VerificationToken {
identifier String
token String #unique
expires DateTime
##unique([identifier, token])
}
What i want to do is be able to fetch the signed in users github username and github related repos, but i dont want to hard code my username, but use the signed in users information to fetch there stuff, how would i do this, am i abke to use there token to access somehow to fetch this information ?

Prisma exclude link table when fetching relation

Does anyone know if Prisma has a way to avoid unnecessary nesting levels when fetching nested objects through the link table?
Schema:
model User {
id String #id #default(cuid())
name String?
email String? #unique
emailVerified DateTime?
image String?
accounts Account[]
sessions Session[]
roles UsersRoles[]
created_at DateTime #default(now())
}
model Role {
id Int #id #default(autoincrement())
name AllowedRoles #default(USER)
users UsersRoles[]
}
model UsersRoles {
userId String
user User #relation(fields: [userId], references: [id])
roleId Int
role Role #relation(fields: [roleId], references: [id])
##id([userId, roleId])
}
In the screenshot you see that I must do
include: {
roles: {
include: {
role: true
}
}
}
to get the role id and name, but I also get the unnecessary data from the link table/pivot table. Can I query the role data directly, without getting the pivot table in the result?
It works with Prisma implicit many to many relationships, but I want to do with explicit
Edit 1:
Found this https://www.prisma.io/docs/guides/database/troubleshooting-orm/help-articles/working-with-many-to-many-relations
Prisma shows an example how to get rid of link table data:
const result = posts.map((post) => {
return { ...post, tags: post.tags.map((tag) => tag.tag) }
})
I guess since even in Prisma docs they do it like this, there is no way to do so during fetching time with Prisma client. But I might be wrong.
Try swapping out your top-level include for a select. Prisma will return all scalar (non-relation) fields by default unless you specify a select object.
relevant docs

Relate existing User and Post in Prisma to create a favorites feature

I want a simple favorite feature. For that I need to connect an existing user with an existing post.
I cannot really find an explanation in the Prisma docs, they only show how to make relations when creating a new post.
Here is my schema:
model User {
uid String #id #default(uuid())
username String? #db.VarChar(24) #unique
favorites FavoritesOnUsers[]
model Post {
id Int #id #default(autoincrement())
title String #db.VarChar(255)
favoritedBy FavoritesOnUsers[]
}
model FavoritesOnUsers {
user User #relation(fields: [userId], references: [uid])
userId String
post Post #relation(fields: [postId], references: [id])
postId Int
##id([userId, postId])
}
So when the user likes a post and adds it to his favorites, how would such a query look like to combine the userId with the postId in the FavoritesOnUsers table?
Creating a record in the junction table should relate both entities:
await prisma.favouritesOnUsers.create({
data: { userId, postId },
});

Typescript + Prisma get object fields from express request

I want to get User's fields from a request body.
Below is my current solution, the reason I use : User is it mandates required fields to be destructed also it gives autocompletion.
const { username, password, email, birthday, country_code, preferences }: User = req.body;
I want to automatically get all fields from req.body. Maybe something like below.
const namedObject = ({} : User = req.body);
User Model
model User {
id Int #id #default(autoincrement())
username String #unique
email String #unique
password String
created_at DateTime #default(now())
birthday DateTime?
country_code String?
preferences Json?
Message Message[]
}
Question
What is the proper solution for this?

Categories