Prisma – 将属性的类型设置为枚举的数组

huangapple go评论103阅读模式
英文:

Prisma - Set property's type as array of enum

问题

这是我的模型:
```ts
model ExampleModel {
  id   String @id @default(auto()) @map("_id") @db.ObjectId
  name String @unique
  foo  ...
}

enum Tags {
  TagA
  TagB
  TagC
}

我想将 foo 的类型设置为 Tags 数组,(foo 的示例值可以是 [ 'TagA', 'TagC' ])。我该如何做?使用 foo Tags[] 会将 foo 的类型设置为 "TagA"[] | undefined


<details>
<summary>英文:</summary>

This is my model: 

model ExampleModel {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String @unique
foo ...
}

enum Tags {
TagA
TagB
TagC
}

I want to set the type of `foo` as an array of Tags, (an example value of `foo` would be `[&#39;TagA&#39;, &#39;TagC&#39;]`. How do I do that? Using `foo Tags[]` sets the type of `foo` as `&quot;TagA&quot;[] | undefined`

</details>


# 答案1
**得分**: 2

如果您想将 `foo` 设为 `Tags` 枚举的数组,您确实可以使用 `foo Tags[]`。然而,类型 "TagA[] | undefined" 表示 foo 可以是 TagA 数组,或者它可以是未定义的(未设置)。这是在 Prisma 中定义数组字段时的预期类型,但它不是必需的,也没有默认值。

如果您希望 foo 始终具有值(即它永远不会是未定义的),您可以通过在默认值中附加一个空数组的 `@default` 指令来将其设置为必需字段,如下所示:

```prisma
model ExampleModel {
  id   String @id @default(auto()) @map("id") @db.ObjectId
  name String @unique
  foo  Tags[] @default([])
}

enum Tags {
  TagA
  TagB
  TagC
}

在这个修改后的模式中,foo 是一个必需字段,如果没有提供值,它将默认为一个空数组。它将始终是 Tags 的数组,永远不会是未定义的。

英文:

If you want to make foo an array of Tags enum, you can indeed use foo Tags[]. However, the type "TagA[] | undefined" means that foo can be an array of TagA, or it can be undefined (not set). This is the expected type when you define an array field in Prisma, but it is not required and does not have a default value.

If you want foo to always have a value (i.e., it can never be undefined), you can make it a required field by appending the @default directive with an empty array as a default value, like so:

model ExampleModel {
  id   String @id @default(auto()) @map(&quot;_id&quot;) @db.ObjectId
  name String @unique
  foo  Tags[] @default([])
}

enum Tags {
  TagA
  TagB
  TagC
}

In this revised schema, foo is a required field that defaults to an empty array if no value is provided. It will always be an array of Tags, never undefined.

huangapple
  • 本文由 发表于 2023年7月17日 23:00:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76705749.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定