简体   繁体   English

如何在查询中包含自定义 SELECT

[英]How can I include custom SELECTs in my queries

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.我不想检索所有 10 篇文章的内容,而是检索它们的开头。

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.在Postgres里,我会发现所有的文章,您可以按照一个created_at领域,并SELECT与内容SELECT left(content, 15)让我的文章内容的第15个字符。

How can I achieve this with Prisma?如何使用 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.谢谢你的帮助。

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:您可以按照 Ryan在这里建议的操作(第二个建议是您引入一个新字段,可能是像excerpt类的excerpt ),或者您可以像这样执行原始查询

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.您可以这样做,但我建议您引入一个新字段,因为LEFT(content, 15)仍将获取整个内容,但会删除第 15 个字符之后的所有内容。

In this example I used TypeScript to determine $queryRaw s generic type parameter T with a CustomArticle which picks only the relevant information we need so we can have a typed return value.在这个例子中,我使用 TypeScript 来确定$queryRaw的泛型类型参数T和一个CustomArticle ,它只选择我们需要的相关信息,以便我们可以有一个类型化的返回值。

This is currently not directly possible with Prisma, so there are two workarounds to this: Prisma 目前无法直接实现这一点,因此有两种解决方法:

  1. Fetch the content and then just display the first 15 characters on the frontend.获取内容,然后只在前端显示前 15 个字符。

  2. Create another field that just holds the first 15 characters of content and select that field.创建只是持有的前15个字符另一个字段content ,并选择相应的字段。

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.我们在这里有一个请求,所以如果你能为此添加一个 👍 以便我们可以查看优先级,那就太好了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM