对于我目前正在制作的博客网站,我需要从数据库中检索最近的文章,以便在博客的主页上显示它们。我不想检索所有最后 10 篇文章的内容,而是检索它们的开头。
在 Postgres 中,我会找到所有文章,按 created_at
字段对它们进行排序,然后使用 SELECT left(content, 15)<
获取我文章内容的前15个字符。SELECT
内容
我如何使用 Prisma 实现这一目标?
我试过了
return prisma.article.findMany({
orderBy: {
createdAt: 'desc',
},
select: {
createdAt: true,
id: true,
title: true,
updatedAt: true,
content: 'left(content, 15)' as any
},
});
但它告诉我它需要一个 bool 值而不是字符串。
感谢您的帮助。
最佳答案
您可以按照 Ryan 建议的 here 进行操作(第二个建议是您引入一个新字段,可能类似于 excerpt
)或者您可以像这样进行 raw query:
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;`
你可以这样做,但我建议你改为引入一个新字段,因为 LEFT(content, 15)
仍会获取全部内容,但会在第 15 个字符后删除所有内容.
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.
关于javascript - 如何在我的查询中包含自定义 SELECT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68456665/