M_x*_*M_x 5 postgresql go go-gorm
我有这样的模型
type yourTableName struct {
Name string `gorm:"type:varchar(50)" json:"name"`
Email string `gorm:"type:varchar(50)" json:"email"`
FieldNameOfJsonb JSONB `gorm:"type:jsonb" json:"fieldnameofjsonb"`
}
Run Code Online (Sandbox Code Playgroud)
我想使用 GORM 将 FieldNameOfJsonb 作为array of objectpostgres插入
就像下面给出的
{
"name": " james",
"email": "james@gmail.com",
"FieldNameOfJsonb": [
{
"someField1": "value",
"someFiedl2": "somevalue",
},
{
"Field1": "value1",
"Fiedl2": "value2",
}
],
Run Code Online (Sandbox Code Playgroud)
Yar*_*ari 11
我在/sf/answers/5014535151/中回答了类似的问题。
在 Gorm 中使用 JSONB 最简单的方法是使用pgtype.JSONB.
Gorm 使用pgx作为它的驱动程序,并pgx具有名为 的包pgtype,其类型名为pgtype.JSONB。
如果您已经pgx按照 Gorm 的指示进行安装,则无需安装任何其他软件包。
此方法应该是最佳实践,因为它使用底层驱动程序并且不需要自定义代码。
type User struct {
gorm.Model
Data pgtype.JSONB `gorm:"type:jsonb;default:'[]';not null"`
}
Run Code Online (Sandbox Code Playgroud)
从数据库获取价值
u := User{}
db.find(&u)
var data []string
err := u.Data.AssignTo(&data)
if err != nil {
t.Fatal(err)
}
Run Code Online (Sandbox Code Playgroud)
将值设置为 DB
u := User{}
err := u.Data.Set([]string{"abc","def"})
if err != nil {
return
}
db.Updates(&u)
Run Code Online (Sandbox Code Playgroud)
M_x*_*M_x 10
只需在 Model.go 中添加以下代码(参考链接)
import (
"errors"
"database/sql/driver"
"encoding/json"
)
// JSONB Interface for JSONB Field of yourTableName Table
type JSONB []interface{}
// Value Marshal
func (a JSONB) Value() (driver.Value, error) {
return json.Marshal(a)
}
// Scan Unmarshal
func (a *JSONB) Scan(value interface{}) error {
b, ok := value.([]byte)
if !ok {
return errors.New("type assertion to []byte failed")
}
return json.Unmarshal(b,&a)
}
Run Code Online (Sandbox Code Playgroud)
DB.Create(&yourTableName)| 归档时间: |
|
| 查看次数: |
19019 次 |
| 最近记录: |