我有一個模型
type FlowTransaction struct {
gorm.Model
Name string
PartnerTransactionReferenceId string
ReconData interface{} `gorm:"type:jsonb"`
DestinationAccountNumber *string
DestinationIfsc *string
Amount uint64
PartnerId uint
FlowId uint
SelfSettle bool
IsSandbox bool
}
從我的 postgres 資料庫中讀取時,我ReconData收到的訊息為unreadable could not resolve interface type. 我嘗試實作 scan 和 value 方法。
type customJson interface{}
func (j *customJson) Scan(value interface{}) error {
return Scan(value, j)
}
func (j customJson) Value() (driver.Value, error) {
return Value(j)
}
func Scan[dtoType any](value interface{}, model *dtoType) error {
bytes, ok := value.([]byte)
if !ok {
return errors.New(fmt.Sprint("Failed to unmarshal JSONB value:", value))
}
err := json.Unmarshal(bytes, model)
return err
}
func Value[dtoType any](j dtoType) ([]byte, error) {
return json.Marshal(j)
}
但它給出了一個錯誤invalid receiver type customJson (pointer or interface type)。你們有什么想法我該如何解決這個問題。任何幫助表示贊賞。
uj5u.com熱心網友回復:
定義 JSON 型別。
import (
"database/sql/driver"
"encoding/json"
"errors"
"fmt"
)
type JSON json.RawMessage
func (j *JSON) Scan(value interface{}) error {
bytes, ok := value.([]byte)
if !ok {
return errors.New(fmt.Sprint("Failed to unmarshal JSONB value:", value))
}
result := json.RawMessage{}
err := json.Unmarshal(bytes, &result)
*j = JSON(result)
return err
}
func (j JSON) Value() (driver.Value, error) {
if len(j) == 0 {
return nil, nil
}
return json.RawMessage(j).MarshalJSON()
}
在模型結構中:
type FlowTransaction struct {
gorm.Model
Name string
PartnerTransactionReferenceId string
ReconData JSON `type:jsonb`
DestinationAccountNumber *string
DestinationIfsc *string
Amount uint64
PartnerId uint
FlowId uint
SelfSettle bool
IsSandbox bool
}
uj5u.com熱心網友回復:
因為 gorm 使用pgx,所以可以使用pgtype包。有JSONB型別
所以你的模型看起來像這樣
import (
...
"github.com/jackc/pgtype"
...
)
type FlowTransaction struct {
gorm.Model
Name string
PartnerTransactionReferenceId string
ReconData pgtype.JSONB `gorm:"type:jsonb"`
DestinationAccountNumber *string
DestinationIfsc *string
Amount uint64
PartnerId uint
FlowId uint
SelfSettle bool
IsSandbox bool
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/508652.html
