Prisma ORM & PostgreSQL applying pagination on related table results - node.js

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,
},
},
},
},
);

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.

prisma connectOrCreate create duplicates or return error

I'm trying to seed a bunch of records, on a table that has a many-to-many relationships with another table.
model Resume {
id Int #id #default(autoincrement())
name String
company String?
logo String?
description String?
startDate DateTime?
endDate DateTime?
createdAt DateTime? #default(now()) #map("created_at")
updatedAt DateTime? #map("updated_at")
deletedAt DateTime? #map("deleted_at")
tags ResumeTag[]
##map("resume")
}
model ResumeTag {
id Int #id #default(autoincrement())
name String #unique
resume Resume[]
##map("resume_tags")
}
on script this is what i use using connectOrCreate ( removed other parts, but this is the gist of it):
const resumeSingle = {
id: 1,
company: 'Company A',
name: 'Software Developer',
logo: 'Logo.svg',
description: '',
startDate: moment('2016-06-01').toISOString(),
endDate: null,
tags: ['Node.JS', 'GraphQL', 'PostgreSQL']
};
const { tags, ...resumeData} = resumeSingle;
await prisma.resume.create({
data: {
...resumeData,
tags: {
connectOrCreate: tags.map(tag => ({
where: { name: tag }, create: { name: tag }
}))
},
},
});
I have several records to insert, some with same repeated tags. However the code only stops with error when a new records has a tag already in the db.
Unique constraint failed on the constraint: `name`.
If I remove the unique on name column in ResumeTag it just add duplicated in the db table (with the same name).
I'm using connectOrCreate wrong here?

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

How can I check if a relation is established/connected?

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?

get posts by tag Id using Prisma.js

How can I get posts by filtering tagId?
I test this code but it doesn't work:
I get all of the posts without filtering!
prisma.post.findMany({
include:
{
Tags:
{
where: { TagId: tagId },
include:
{
Tag: true
}
}
},
})
schema.prisma:
model Post {
id Int #id #default(autoincrement())
title String
tags PostTags[]
}
model PostTags {
id Int #id #default(autoincrement())
post Post? #relation(fields: [postId], references: [id])
tag Tag? #relation(fields: [tagId], references: [id])
postId Int?
tagId Int?
}
model Tag {
id Int #id #default(autoincrement())
name String #unique
posts PostTags[]
}
how can I fix the problem?
You would need to filter it inside the main query and not in include. include is only for fetching relations and then filtering inside them, it will not affect the main query.
Your final query would look like:
await prisma.post.findMany({
where: { tags: { some: { tag: { id: 1 } } } }
})
You can read more about querying for relations here.

Resources