Reputation: 985
For a blog website I am currently making I need to retrieve the recent articles from the database to show them on the main page of the blog. I do not want to retrieve the content of all 10 last articles but rather the beginning of them.
In Postgres, I would find all the articles, sort them by a created_at
field, and SELECT
the content with SELECT left(content, 15)
to get the 15 first characters of the content of my article.
How can I achieve this with Prisma?
I tried
return prisma.article.findMany({
orderBy: {
createdAt: 'desc',
},
select: {
createdAt: true,
id: true,
title: true,
updatedAt: true,
content: 'left(content, 15)' as any
},
});
But it tells me that it is expecting a boolean value instead of string.
Thanks for your help.
Upvotes: 3
Views: 1530
Reputation: 41
You could do what Ryan suggested here (the second suggestion being that you introduce a new field, maybe something like excerpt
) OR you could do a raw query like so:
import { Article } from '@prisma/client';
type CustomArticle = Pick<Article, 'id' | 'title' | 'content' | 'createdAt' | 'updatedAt'>;
const prisma = /* your prisma client */
const result = await prisma.$queryRaw<CustomArticle[]>`SELECT id, title, LEFT(content, 15) as content, createdAt, updatedAt FROM Article;`
You can do this but I suggest you introduce a new field instead as LEFT(content, 15)
will still fetch the whole content but strip everything after the 15th character.
In this example I used TypeScript to determine
$queryRaw
s generic type parameterT
with aCustomArticle
which picks only the relevant information we need so we can have a typed return value.
Upvotes: 2
Reputation: 6327
This is currently not directly possible with Prisma, so there are two workarounds to this:
Fetch the content and then just display the first 15 characters on the frontend.
Create another field that just holds the first 15 characters of content
and select that field.
We have a request for this here so it would be great if you could add a 👍 to this so that we can look at the priority.
Upvotes: 0