JSON
示例使用以下 prisma 模式
model Log {
id String @id @default(cuid())
date DateTime @default(now())
message String
meta Json
}
JSON 在 Go 客户端中的工作原理
JSON 通过使用 Go 的 json.RawMessage
数据结构来实现。它在幕后是一个 []byte
,这意味着您可以使用您已知的 API 在 Go 客户端中处理非结构化 json 数据。
您可以直接使用 []bytes,但通常您会将此数据从现有结构体中编组,或将数据反编组到给定的结构体变量中。
写入 JSON 数据
type LogInfo struct {
Service string `json:"service"`
}
logInfo := &LogInfo{
Service: "deployment/api",
}
infoBytes, err := json.Marshal(logInfo)
if err != nil {
panic(err)
}
_, err = client.Log.CreateOne(
db.Log.Message.Set("/api/graphql: status code 400"),
db.Log.Info.Set(infoBytes),
db.Log.ID.Set("123"),
).Exec(ctx)
if err != nil {
panic(err)
}
读取 JSON 数据
log, err := client.Log.FindUnique(
db.Log.ID.Equals("123"),
).Exec(ctx)
if err != nil {
panic(err)
}
// log.Info is of type json.RawMessage, so this will contain binary data such as [123 34 97 116 116 ...]
// however, if we format it with %s, we can convert the contents to a string to see what's inside:
log.Printf("log info: %s", log.Info)
// to unmarshal this information into a specific struct, we make use of Go's usual handling of json data:
type LogInfo struct {
Service string `json:"service"`
}
var info LogInfo
if err := json.Unmarshal(log.Info, &info); err != nil {
panic(err)
}
log.Printf("log info: %+v", info)
查询 JSON
您可以使用 Path
和 JSON 查询的组合来过滤 JSON 字段。请注意,语法在不同的数据库之间有所不同。
actual, err := client.User.FindFirst(
User.Meta.Path([]string{"service"}),
User.Meta.StringContains("api"),
).Exec(ctx)
actual, err := client.User.FindFirst(
User.Meta.Path([]string{"service"}),
// Note that Equals accepts JSON, so strings need to be surrounded with quotes
User.Meta.Equals(JSON(`"deployment/api"`)),
).Exec(ctx)
有关所有 json 过滤器和更多示例查询的更多信息,请查看 Prisma JSON 过滤器文档 (在新标签页中打开).