我如何从Prisma类获取所有领域?

发布于 2025-01-17 11:11:55 字数 986 浏览 2 评论 0原文

我在Prisma模式中有这两个表:

model Accounts {
  id Int @id @default(autoincrement())
  name String @db.VarChar(100)
  description String? @db.VarChar(255)
  timeZone Int @default(0)
  tableBusinessApplication AccountsBusinessApplications[]
}

model AccountsBusinessApplications {
  id Int @id @default(autoincrement())
  account Accounts @relation(fields: [accountId], references: [id])
  accountId Int
  name String @db.VarChar(100)
  identification String @db.VarChar(100)
  secretKey String @db.VarChar(32)
}

我有关注的代码:

const name = 'Accounts'
prisma[name].findFirst({
  where: { id: 1}
}).then(result => { console.log(result) })

结果我有:

{
  id: 1,
  name: 'test',
  description: 'test description',
  timeZone: 0
}

但是我看不到' tablebusinessapplication '内部。如果我只知道头等舱名称“ 帐户”,并且我不能在查询中使用' include ',我该如何获取所有数据?

我尝试找到如何使用Prisma类获取字段列表,但似乎没有。

I have these two tables in Prisma schema:

model Accounts {
  id Int @id @default(autoincrement())
  name String @db.VarChar(100)
  description String? @db.VarChar(255)
  timeZone Int @default(0)
  tableBusinessApplication AccountsBusinessApplications[]
}

model AccountsBusinessApplications {
  id Int @id @default(autoincrement())
  account Accounts @relation(fields: [accountId], references: [id])
  accountId Int
  name String @db.VarChar(100)
  identification String @db.VarChar(100)
  secretKey String @db.VarChar(32)
}

I have the follow piece of code:

const name = 'Accounts'
prisma[name].findFirst({
  where: { id: 1}
}).then(result => { console.log(result) })

and as a result I have:

{
  id: 1,
  name: 'test',
  description: 'test description',
  timeZone: 0
}

but I don't see 'tableBusinessApplication' inside. How can I get all data if I know only first class name "Accounts" and I can't use 'Include' in Query?

I try to find how to get a list of fields using prisma class, but it seems like there is nothing.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

又怨 2025-01-24 11:11:55

从 Prisma 4 开始:

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

console.log("Account fields:", Prisma.dmmf.datamodel.models.find(model => model.name === "Account").fields)

As of Prisma 4:

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

console.log("Account fields:", Prisma.dmmf.datamodel.models.find(model => model.name === "Account").fields)
笑忘罢 2025-01-24 11:11:55

从Prisma 5开始:

const allowedFields = Object.keys(prisma[this.modelName].fields)

As of Prisma 5:

const allowedFields = Object.keys(prisma[this.modelName].fields)
我恋#小黄人 2025-01-24 11:11:55

您可以使用 Prisma 的 DMMF 属性来获取模型字段的名称。

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

const prisma = new PrismaClient();


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

  // @ts-ignore
  console.log('dmmf', prisma._dmmf.modelMap.Accounts.fields);
}
main()
  .catch((e) => {
    throw e;
  })
  .finally(async () => {
    await prisma.$disconnect();
  });

以下是输出。

dmmf [
  {
    name: 'id',
    kind: 'scalar',
    isList: false,
    isRequired: true,
    isUnique: false,
    isId: true,
    isReadOnly: false,
    type: 'Int',
    hasDefaultValue: true,
    default: { name: 'autoincrement', args: [] },
    isGenerated: false,
    isUpdatedAt: false
  },
  {
    name: 'name',
    kind: 'scalar',
    isList: false,
    isRequired: true,
    isUnique: false,
    isId: false,
    isReadOnly: false,
    type: 'String',
    hasDefaultValue: false,
    isGenerated: false,
    isUpdatedAt: false
  },
  {
    name: 'description',
    kind: 'scalar',
    isList: false,
    isRequired: false,
    isUnique: false,
    isId: false,
    isReadOnly: false,
    type: 'String',
    hasDefaultValue: false,
    isGenerated: false,
    isUpdatedAt: false
  },
  {
    name: 'timeZone',
    kind: 'scalar',
    isList: false,
    isRequired: true,
    isUnique: false,
    isId: false,
    isReadOnly: false,
    type: 'Int',
    hasDefaultValue: true,
    default: 0,
    isGenerated: false,
    isUpdatedAt: false
  },
  {
    name: 'tableBusinessApplication',
    kind: 'object',
    isList: true,
    isRequired: true,
    isUnique: false,
    isId: false,
    isReadOnly: false,
    type: 'AccountsBusinessApplications',
    hasDefaultValue: false,
    relationName: 'AccountsToAccountsBusinessApplications',
    relationFromFields: [],
    relationToFields: [],
    isGenerated: false,
    isUpdatedAt: false
  }
]

请注意,DMMF 是内部 API,在未来版本中可能会有更改。

You can use Prisma's DMMF property to get the name of the fields of a model.

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

const prisma = new PrismaClient();


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

  // @ts-ignore
  console.log('dmmf', prisma._dmmf.modelMap.Accounts.fields);
}
main()
  .catch((e) => {
    throw e;
  })
  .finally(async () => {
    await prisma.$disconnect();
  });

Here's the output

dmmf [
  {
    name: 'id',
    kind: 'scalar',
    isList: false,
    isRequired: true,
    isUnique: false,
    isId: true,
    isReadOnly: false,
    type: 'Int',
    hasDefaultValue: true,
    default: { name: 'autoincrement', args: [] },
    isGenerated: false,
    isUpdatedAt: false
  },
  {
    name: 'name',
    kind: 'scalar',
    isList: false,
    isRequired: true,
    isUnique: false,
    isId: false,
    isReadOnly: false,
    type: 'String',
    hasDefaultValue: false,
    isGenerated: false,
    isUpdatedAt: false
  },
  {
    name: 'description',
    kind: 'scalar',
    isList: false,
    isRequired: false,
    isUnique: false,
    isId: false,
    isReadOnly: false,
    type: 'String',
    hasDefaultValue: false,
    isGenerated: false,
    isUpdatedAt: false
  },
  {
    name: 'timeZone',
    kind: 'scalar',
    isList: false,
    isRequired: true,
    isUnique: false,
    isId: false,
    isReadOnly: false,
    type: 'Int',
    hasDefaultValue: true,
    default: 0,
    isGenerated: false,
    isUpdatedAt: false
  },
  {
    name: 'tableBusinessApplication',
    kind: 'object',
    isList: true,
    isRequired: true,
    isUnique: false,
    isId: false,
    isReadOnly: false,
    type: 'AccountsBusinessApplications',
    hasDefaultValue: false,
    relationName: 'AccountsToAccountsBusinessApplications',
    relationFromFields: [],
    relationToFields: [],
    isGenerated: false,
    isUpdatedAt: false
  }
]

Please note that DMMF is an internal API and may have changes in future versions.

三月梨花 2025-01-24 11:11:55

提供的解决方案已过时用于Prisma v5.6.0。以下是我不完整但功能上的代码,用于从Prisma架构中读取并生成JSON,我将其用于Hygen的模板生成。

import { readFileSync, writeFileSync } from 'fs'
import { join } from 'path'

interface Field {
  name: string;
  type: string;
  isUnique: boolean;
  isObjectId: boolean;
}

interface UniqueConstraint {
  fields: string[];
}

interface Index {
  fields: string[];
}

interface Model {
  name: string;
  tableName?: string; // Database table name if specified
  fields: Field[];
  uniqueConstraints: UniqueConstraint[];
  indexes: Index[];
}

// Basic parsing of model definitions
const parseModels = (schema: string): Model[] => {
  const modelRegex = /model (\w+) {([\s\S]*?)^}/gm
  let match
  const models: Model[] = []

  while ((match = modelRegex.exec(schema)) !== null) {
    const modelName = match[1]
    const modelBody = match[2]

    const fields = modelBody.trim().split('\n')
      .filter(line => line && !line.startsWith('@') && !line.startsWith('@@'))
      .map((line) => {
        const [name, type] = line.trim().split(/\s+/)
        const isUnique = line.includes('@unique')
        const isObjectId = line.includes('@db.ObjectId');

        if (name.includes('@@')) {
          return null
        }
        return { name, type, isUnique, isObjectId }
      }).filter(field => field !== null)

    // Extract table mapping
    const tableMappingMatch = modelBody.match(/@@map\(["'](.+?)["']\)/)
    const tableName = tableMappingMatch ? tableMappingMatch[1] : undefined

    // Extract unique constraints
    const uniqueConstraints: UniqueConstraint[] = []
    const uniqueRegex = /@@unique\(\[([^\]]+)\]\)/g
    let uniqueMatch
    while ((uniqueMatch = uniqueRegex.exec(modelBody)) !== null) {
      const fields = uniqueMatch[1].split(',').map(field => field.trim())
      uniqueConstraints.push({ fields })
    }

    // Extract indexes
    const indexes: Index[] = []
    const indexRegex = /@@index\(\[([^\]]+)\]\)/g
    let indexMatch
    while ((indexMatch = indexRegex.exec(modelBody)) !== null) {
      const fields = indexMatch[1].split(',').map(field => field.trim())
      indexes.push({ fields })
    }

    models.push({ name: modelName, tableName, fields, uniqueConstraints, indexes })
  }

  return models
}

const parsePrismaSchema = (schemaPath: string): Model[] => {
  const schema = readFileSync(schemaPath, 'utf8')
  return parseModels(schema)
}

const main = () => {
  const schemaPath = join(__dirname, '../../prisma/schema.prisma')
  const models = parsePrismaSchema(schemaPath)
  const schemaJsonPath = join(__dirname, '../../prisma/schema.json')
  const schemaJson = JSON.stringify(models, null, 2)
  // console.log(schemaJson)
  writeFileSync(schemaJsonPath, schemaJson)
}

main()

The provided solutions are outdated for Prisma v5.6.0. Below is my incomplete but functional code for reading from a Prisma schema and generating JSON, which I use for template generation with Hygen.

import { readFileSync, writeFileSync } from 'fs'
import { join } from 'path'

interface Field {
  name: string;
  type: string;
  isUnique: boolean;
  isObjectId: boolean;
}

interface UniqueConstraint {
  fields: string[];
}

interface Index {
  fields: string[];
}

interface Model {
  name: string;
  tableName?: string; // Database table name if specified
  fields: Field[];
  uniqueConstraints: UniqueConstraint[];
  indexes: Index[];
}

// Basic parsing of model definitions
const parseModels = (schema: string): Model[] => {
  const modelRegex = /model (\w+) {([\s\S]*?)^}/gm
  let match
  const models: Model[] = []

  while ((match = modelRegex.exec(schema)) !== null) {
    const modelName = match[1]
    const modelBody = match[2]

    const fields = modelBody.trim().split('\n')
      .filter(line => line && !line.startsWith('@') && !line.startsWith('@@'))
      .map((line) => {
        const [name, type] = line.trim().split(/\s+/)
        const isUnique = line.includes('@unique')
        const isObjectId = line.includes('@db.ObjectId');

        if (name.includes('@@')) {
          return null
        }
        return { name, type, isUnique, isObjectId }
      }).filter(field => field !== null)

    // Extract table mapping
    const tableMappingMatch = modelBody.match(/@@map\(["'](.+?)["']\)/)
    const tableName = tableMappingMatch ? tableMappingMatch[1] : undefined

    // Extract unique constraints
    const uniqueConstraints: UniqueConstraint[] = []
    const uniqueRegex = /@@unique\(\[([^\]]+)\]\)/g
    let uniqueMatch
    while ((uniqueMatch = uniqueRegex.exec(modelBody)) !== null) {
      const fields = uniqueMatch[1].split(',').map(field => field.trim())
      uniqueConstraints.push({ fields })
    }

    // Extract indexes
    const indexes: Index[] = []
    const indexRegex = /@@index\(\[([^\]]+)\]\)/g
    let indexMatch
    while ((indexMatch = indexRegex.exec(modelBody)) !== null) {
      const fields = indexMatch[1].split(',').map(field => field.trim())
      indexes.push({ fields })
    }

    models.push({ name: modelName, tableName, fields, uniqueConstraints, indexes })
  }

  return models
}

const parsePrismaSchema = (schemaPath: string): Model[] => {
  const schema = readFileSync(schemaPath, 'utf8')
  return parseModels(schema)
}

const main = () => {
  const schemaPath = join(__dirname, '../../prisma/schema.prisma')
  const models = parsePrismaSchema(schemaPath)
  const schemaJsonPath = join(__dirname, '../../prisma/schema.json')
  const schemaJson = JSON.stringify(models, null, 2)
  // console.log(schemaJson)
  writeFileSync(schemaJsonPath, schemaJson)
}

main()

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文