prisma 中是否可以按字符串长度进行过滤?

Is it possible in prisma to filter by string length?

在 prisma 中是否可以按字符串长度进行过滤?

例如,我想接收名称长度为10个字符的记录。

您需要使用 Raw Query 按字符串长度过滤记录。

这是一个如何实现它的示例。 考虑这个模型

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model Employee {
  employeeId Int      @id @default(autoincrement())
  first_name String
  hire_date  DateTime
}

此查询将过滤掉 first_name 长度小于 5 个字符的记录

import { Prisma, PrismaClient } from '@prisma/client';

const prisma = new PrismaClient({
  log: ['query', 'info', 'warn'],
});

// A `main` function so that you can use async/await
async function main() {

  const result =
    await prisma.$queryRaw`SELECT * FROM "public"."Employee" WHERE LENGTH(first_name) <= 5`;

  console.log(result);
}
main()
  .catch((e) => {
    throw e;
  })
  .finally(async () => {
    await prisma.$disconnect();
  });

这是输出

prisma:info Starting a postgresql pool with 13 connections.
prisma:query SELECT * FROM "public"."Employee" WHERE LENGTH(first_name) <= 5
[
  {
    employeeId: 1,
    first_name: 'John',
    hire_date: '2022-03-10T00:00:00+00:00'
  }
]