How can I check if a relation is established/connected? - node.js

I have this prisma schema which looks like this:
model UserProfile {
createdAt DateTime #default(now())
updatedAt DateTime #updatedAt
id String #id #default(cuid())
username String #unique
avatar String #default("defaultAvatar")
banner String #default("defaultBanner")
name String #default("A New Gem User")
verified Boolean #default(false)
gemStaff Boolean #default(false)
gender Gender[]
location String?
verifiedDescription String?
bio String?
author User #relation(fields: [authorId], references: [id])
authorId String #unique
posts Post[] #relation("UserProfilePosts")
postGroups PostGroup[] #relation("UserProfilePostGroups")
giveaways Giveaway[]
categories UserCategory[]
following UserProfile[] #relation("UserFollows")
followers UserProfile[] #relation("UserFollows")
comments Comment[] #relation("UserProfileComments")
subComments SubComment[] #relation("UserProfileSubComments")
likedPosts Post[]
likedComments Comment[] #relation("UserProfileLikesComments")
likedSubComments SubComment[] #relation("UserProfileLikesSubComments")
groupsJoined UserGroup[]
blocking UserProfile[] #relation("UserBlocked")
blockedBy UserProfile[] #relation("UserBlocked")
favoriteGroups FavoriteGroup[] #relation("UserProfileFavoritedGroups")
views Int #default(0)
}
model Post {
createdAt DateTime #default(now())
updatedAt DateTime #updatedAt
public Boolean #default(true)
id String #id #default(cuid())
author UserProfile #relation("UserProfilePosts", fields: [authorId], references: [id])
authorId String
favoritedGroupsAdded FavoriteGroup[]
content String
views Int #default(0)
likedBy UserProfile[]
tags PostTag[]
comments Comment[] #relation("PostComments")
subComments SubComment[] #relation("PostSubComments")
group PostGroup? #relation("PostGroups", fields: [groupId], references: [id])
groupId String?
}
When you like something, you create a relation from UserProfile to Post. When you dislike something, you just delete the relation. Does anyone know how can I check a relation between one UserProfile to one Post so I can figure out if someone liked a post?

Related

How is the way for me to transfer data from an ITEM that is related to my salesman in the database?

I have this relationship in my schema:
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model Salesman {
id String #id #default(uuid())
username String #unique
password String
contact String #unique
item Item[]
##map("salesman")
}
model Buyer {
id String #id #default(uuid())
username String #unique
password String
##map("buyer")
}
model Item {
id String #id #default(uuid())
item_name String
float_item String
price String
type_skin String
salesman Salesman? #relation(fields: [id_salesman], references: [id])
id_salesman String?
##map("item")
}
i try like this
import { prisma } from "../../../../database/prismaClient" interface IRequest{ username: String, contact: String, id: String } export class GetItemUseCase { async execute({ username, contact, id}: IRequest ){ const info = await prisma.item.findFirst({ where:{id}, select:{ salesman { username, contact, }, } }) } } I tried something like this.
and I'm trying to make a way where when choosing an ITEM, I get the data from that salesman.
but I have no idea how.
What better way to inform?
Sorry, I'm a beginner.
I've tried verifying the relationships and I've tried searching the database.

Cannot return null for non-nullable field Mutation.createAds graphql error

I'm getting Cannot return null for non-nullable field Mutation.createAds. Error in altair graphql any help
I'm trying to upload multiples photos but I'm getting this error!
Hi, I'm getting Cannot return null for non-nullable field Mutation.createAds. Error in altair graphql any help
I'm trying to upload multiples photos but I'm getting this error
type ads {
id: String
user: User
titel: String
discription: String
photo: [photos]
createdAt: String
updatedAt: String
}
type photos{
id: String
photo: String
Adses: ads
createdAt: String
updatedAt: String
}
type Mutation{
createAds( titel: String
discription: String
photo: [Upload]):ads!
}
}
Resolvers
createAds: async (_, {titel,
discription,photo},{LogedInUser}) =>{
userProtect(LogedInUser)
const simo= await MultiplereadFiles(photo)
console.log(simo)
const create = Client.ads.create({data:{
titel,
discription,
photos:simo,
user:{
connect:{
id:LogedInUser.id
}
}
}})
},
Prisma schema
model ads {
id Int #id
user User #relation(fields: [userId], references: [id])
titel String?
discription String
photo photos[]
files String
createdAt DateTime #default(now())
updatedAt DateTime #updatedAt
userId Int
}
model photos {
id Int #id
Adses ads #relation(fields: [adsId], references: [id])
createdAt DateTime #default(now())
updatedAt DateTime #updatedAt
adsId Int
}
The schema indicates a required response.
From the resolver snippet you shared, it seems there's no return to the function. Could it be the reason?
Either that, or there's something broken in your Client.ads.create logic

prisma - How to impose condition to the last record of a many to many relationship

My schema:
model Order {
id Int #id #default(autoincrement())
OrderStatusLogs OrderStatusLog[]
}
model OrderStatusLog {
id Int #id #default(autoincrement())
status OrderStatus
createdAt DateTime #default(now())
updatedAt DateTime #updatedAt
orderId Int
Order Order #relation(fields: [orderId], references: [id])
}
enum OrderStatus {
ONE
TWO
THREE
}
The important OrderStatusLog to me is the last one, a practical example of the query I want to achieve:
Select all orders which the last status is X, take 10 from cursor 5
Observation: I'm using pagination, so if I needed to do 2 queries I would prefer to write I raw query instead.

Prisma ORM & PostgreSQL applying pagination on related table results

I am using Prisma ORM with typescript and trying to apply pagination on the related table data. I couldn't find any detailed information in the official documentation of the Prisma about the topic (
https://www.prisma.io/docs/concepts/components/prisma-client/relation-queries and
https://www.prisma.io/docs/concepts/components/prisma-client/pagination
). I'm trying to get the results of below SQL query but Prisma doesn't allow to pass any take or skip params on the indexes data. Thanks for help.
Update: I have added an another query at the end of the post and it is working correctly. Probably the first query that I've posted was wrong but I want to hear the explanation from someone who can explain the issue better.
SELECT title FROM indexes as idxs
INNER JOIN index_users idxu ON (idxu.index_id = idxs.id) WHERE
idxu.user_id = 986
LIMIT 2;
Which corresponds to (intuitively)
const result = await this.client.indexUsers.findMany(
{
where: {
userId: 986,
},
select: {
indexes: {
take: 2, // <-- Doesn't allow this
select: {
title: true,
},
},
},
},
);
Prisma schema of the related tables
model indexes {
id Int #id(map: "pk_indexes") #default(autoincrement())
title String? #db.VarChar(255)
slug String? #db.VarChar(255)
publicRights enum_index_visibility? #default(off) #map("public_rights")
privateLinkRights enum_index_visibility? #default(off) #map("private_link_rights")
privateLinkCode String? #map("private_link_code") #db.VarChar(50)
clonedFrom Int? #map("cloned_from")
createdAt DateTime #default(now()) #map("created_at") #db.Timestamptz(6)
updatedAt DateTime #default(now()) #map("updated_at") #db.Timestamptz(6)
index_users IndexUsers[]
invitations invitations[]
links links[]
}
model IndexUsers {
id Int #id(map: "pk_index_users") #default(autoincrement())
indexId Int #map("index_id")
userId Int #map("user_id")
permission enum_index_users_role? #default(view)
createdAt DateTime #default(now()) #map("created_at") #db.Timestamptz(6)
updatedAt DateTime #default(now()) #map("updated_at") #db.Timestamptz(6)
indexes indexes #relation(fields: [indexId], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "fk_index_users_indexes")
users users #relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "fk_index_users_users")
##map("index_users")
}
model users {
id Int #id(map: "pk_users") #default(autoincrement())
name String? #db.VarChar(100)
username String? #db.VarChar(100)
email String? #db.VarChar(100)
password String? #db.VarChar(255)
picture String? #db.VarChar(255)
location String? #db.VarChar(255)
visibility Boolean #default(true)
bio String? #db.VarChar(255)
urlWeb String? #map("url_web") #db.VarChar(255)
urlFacebook String? #map("url_facebook") #db.VarChar(255)
urlTwitter String? #map("url_twitter") #db.VarChar(255)
urlInstagram String? #map("url_instagram") #db.VarChar(255)
urlPatreon String? #map("url_patreon") #db.VarChar(255)
verified Boolean #default(false)
externalLogin Boolean? #map("external_login")
apiKey String? #map("api_key") #db.VarChar(255)
zapierToken String? #map("zapier_token") #db.VarChar(255)
createdAt DateTime #default(now()) #map("created_at") #db.Timestamptz(6)
updatedAt DateTime #default(now()) #map("updated_at") #db.Timestamptz(6)
verificationKey String? #map("verification_key") #db.VarChar(255)
index_users IndexUsers[]
user_token UserToken[]
}
Updated query which works correctly
const result = await this.client.indexes.findMany(
{
take: 2,
select: {
title: true,
},
where: {
index_users: {
some: {
userId: 986,
},
},
},
},
);

prisma query postgresql into nestJs

I have a problem as following:
schema:
model company {
id Int #id #default(autoincrement())
name String?
services company_service[]
...
}
model company_service {
companyId Int #map("company_id")
serviceId Int #map("service_id")
company company? #relation(fields: [companyId], references: [id])
service service? #relation(fields: [serviceId], references: [id])
##id([companyId, serviceId])
}
model service {
id Int #id #default(autoincrement())
name String?
companies company_service[]
jobs job[]
}
model job {
id Int #id #default(autoincrement())
customerId Int? #map("customer_id")
serviceId Int? #map("service_id")
addressId Int? #map("address_id")
status Int? #default(1) // 1: Available, 2: In Progress, 3:Cancel ,4: Completed,
customer customer? #relation(fields: [customerId], references: [id])
service service? #relation(fields: [serviceId], references: [id])
}.
I need to execute the query:
SELECT company_id, count(j.status) as numberOfWorkComplete
FROM company_service sv, job j
WHERE sv.service_id = j.service_id and j.status = 4
GROUP BY company_id
I have the result of the above query but is there any way i can still get that result without having to write sql? thanks
Currently a raw query is the only way to do this. We have a request for the same here so it would be great if you could add a 👍 to this so that we can look at the priority.

Resources