Find record with an empty relation - prisma

Say I have this prisma schema with an implicit m:n-relation of Post and Tag
model Post {
id String #id
tags Tag[]
}
model Tag {
id Int #id #default(autoincrement())
posts Post[]
}
How do I find the first Post that has no associated Tags?
prisma.post.findFirst({
where: {
tags: {
// are nonexistent (something like count === 0?)
},
},
}),
Thanks for the help :)

You can probably use orderBy by count of tags in ascending order and get the first one? Like that:
prisma.post.findFirst({
orderBy: { tags: { _count: 'asc' } },
});

Searching on the internet I've found a link where the official documentation gives information on how to manage lists --> here
There it gives this example:
const posts = await prisma.post.findMany({
where: {
tags: {
isEmpty: true,
},
},
})
Try adapting that to your own situation.

Related

How to update composite type model in Prisma?

I am trying to implement updation in a composite-type model in Prisma.
Here is my data structure:
{
"name":"toy",
"data":{
"sports":{
"currentState":"false"
},
"business":{
"currentState":"false"
}
}
}
Here I my code for updating:
const updatedSource = await prisma.sources.update({
where: {
name: 'toy'
},
data: {
data: {
sports: {
currentState: "true"
}
}
},
})
Here is my schema file
type SourcesData {
business SourcesDataState
sports SourcesDataState
}
type SourcesDataState {
currentState StateData[]
}
type StateData {
title String
url String
}
model sources {
id String #id #default(auto()) #map("_id") #db.ObjectId
data SourcesData
name String #unique
}
When I execute the above logic I get error as:Unknown arg `sports` in data.data.sports for type SourcesDataUpdateEnvelopeInput. Did you mean `set`? Available args:
Please guide what I am missing while updating.
The TypeScript should be pretty helpful in telling you what arguments you can or cannot use when interacting with Prisma. I strongly recommend using a code editor that includes TypeScript typehinting/Intellisense so you can see errors and warnings about your TypeScript usage as you are developing with Prisma.
Where it says Available args in your error, that should tell you the arguments that prisma.sports.update actually expects. If I had to guess (this may not be accurate, but you HAVE to look at the TypeScript to know exactly what it's supposed to be), it should look something like this:
const updatedSource = await prisma.sources.update({
where: {
name: 'toy'
},
data: {
data: {
update: {
sports: {
update: {
currentState: {
set: ["true"]
}
}
}
}
}
},
})
I strongly recommend reading Prisma's documentation on updating related/nested records: https://www.prisma.io/docs/concepts/components/prisma-client/relation-queries#update-a-specific-related-record
let typeEncounter = await prisma.encounter.update({
where: {
id
},
data: {
[property]: {
update: {
[subProperty] : value,
},
},
},
}
)
I get a receive the error Unknown arg update in data..update
I have seen some people mention nesting updates but no official documentation and can't seem to get this straightened out. Anybody have any ideas? The property and subproperty are largely irrelevant here, just examples. The code works fine aside from updated a subfield of a type (mongoDB prisma). Without the update the entire type gets overwritten rather than the selected field.

How do I perform a count on a relation with a where clause in prisma?

I have the following query which gives all posts and a count of all comments. Now I'd like to get a count of all comments with the post that have the approved field set to true. I can't seem to figure this out.
prisma.post.findMany({
include: {
_count: { select: { Comment: true } },
},
});
Thanks for any help.
You would need to use Raw Query to achieve this as the filter on _count for relations is not supported yet.
Here's the Feature Request for the same: Ability to filter count in "Count Relation Feature"
[Edit: 14-Nov-2022]
Prisma has added support for filteredRelationCount since version 4.3.0
Available since 4.3.0.
enable in your schema file:
generator client {
provider = "prisma-client-js"
previewFeatures = ["filteredRelationCount"] << add this
}
and then query:
await prisma.post.findMany({
select: {
_count: {
select: {
comment: { where: { approved: true } },
},
},
},
})

PRISMA 2.0 - I need help to delete a record inside a field with relationship list

i am on this challange since Monday... please help me? Check my models.
model User {
id String #id #default(cuid())
bookmarks Home[] #relation(name: "UserBookmarks")
}
model Home {
bookmarkedBy User? #relation(name: "UserBookmarks", fields: [userId], references: [id])
userId String?
}
This example is: ONE PERSON can have MULTIPLE Homes in their BOOKMARKS, ok?
My PATCH it works fine, check above.
const home = await prisma.home.update({ where: { id: "123" }, data: { userId: "my-user-id", }, });
When i see the content in PRISMA STUDIO... works fine... i have a list of Homes in bookmarks field. PERFECT.
BUT NOW... how i can DELETE a BOOKMARK in this CASE?
i tried eveything... but i cant understand how i can do that :-( I tried this code bellow:
const home = await prisma.home.delete({ where: { userId: "my-user-id", }, });
AND
const user = await prisma.user.delete({ where: { bookmarks: "my-home-id", }, });
In this case Above... appears this message:
{
"message": "\nInvalid prisma.home.delete() invocation:\n\n{\n where: {\n userId: 'cl3he5om60008you1geu5hbpa'\n ~~~~~~\n }\n}\n\nUnknown arg userId in where.userId for type HomeWhereUniqueInput. Did you mean id? Available args:\ntype HomeWhereUniqueInput {\n id?: String\n}\n\n"
}
HELP ME GUYS!
Thanks guys

count self relation on Prisma error: table name specified more than once

I am trying to count a self relation (followers) in Prisma2 (using PostgreSQL)
Model:
model User {
id String #id #default(cuid())
following User[] #relation(name: "UserFollows")
followers User[] #relation(name: "UserFollows")
}
Query:
const user = await prisma.user.findUnique({
where: { id: userId },
include: {
_count: {
select: { followers: true, following: true },
},
},
});
(using previewFeatures = ["selectRelationCount"]) and getting the following error:
Invalid prisma.user.findUnique() invocation:
Error occurred during query execution: ConnectorError(ConnectorError
{ user_facing_error: None, kind: QueryError(Error { kind: Db, cause:
Some(DbError { severity: "ERROR", parsed_severity: Some(Error), code:
SqlState("42712"), message: "table name "User" specified more than
once", detail: None, hint: None, position: None, where_: None, schema:
None, table: None, column: None, datatype: None, constraint: None,
file: Some("parse_relation.c"), line: Some(423), routine:
Some("checkNameSpaceConflicts") }) }) })
Does anybody have any idea of what I am doing wrong?
This is a known issue with self-relations and we hope to fix it soon. If you want to track this bug, follow this github issue. Please feel free to add a comment to explain your use case/problem over there.
In the meantime, here are some workarounds that you can use:
Find count using nested read
You can use a nested read to return all the records in followers and following and find the length of those arrays to get the count. This seems like the most straightforward way, so long as you're okay with fetching all the followers/following records.
const user = await prisma.user.findUnique({
where: {
id: userId,
},
include: {
followers: true,
following: true,
},
});
let followerCount = user.followers.length;
let followingCount = user.following.length;
Find count using separate count queries.
Alternatively, you can use the count API to find followers and following counts for a certain user.
// number of followers for some user "x" = number of times x.id appaers in "following" relation of other users.
const followerCount = await prisma.user.count({
where: {
following: {
some: {
id: userId,
},
},
},
});
// number of users that user "x" is following = number of times x.id appaers in "followers" relation of other users.
const followingCount = await prisma.user.count({
where: {
followers: {
some: {
id: userId,
},
},
},
});
Change schema to use explicit many-to-many notation
If you're okay with slightly tweaking your schema, you can explicitly define the many-to-many relation table.
model Follows {
follower User #relation("follower", fields: [followerId], references: [id])
followerId String
following User #relation("following", fields: [followingId], references: [id])
followingId String
##id([followerId, followingId])
}
model User {
id String #id #default(cuid())
followers Follows[] #relation("follower")
following Follows[] #relation("following")
}
You should be able to run the count query without issues in this way.

How do you filter for records which have no related records using Prisma?

Using the schema from the Prisma docs as an example, I want to query Users for any users which do not have any posts. I can hack it like this, so that it retrieves every user where none of the posts have an ID greater than 0, but it's not very elegant. Is there a better way to do this?
const result = await prisma.user.findMany({
where: {
post: {
none: {
id: { gt: 0 }
}
}
}
})
You can do it like this:
prisma.user.findMany({ where: {
posts: { none: {} }
}})