[英]Nested json unmarshaling with 2d slices into struct not working in golang
[英]Golang Gorm working with slices and postgres' jsob field
我需要保存 [] 或具有不同 integer 值(如 [1、7、8])的列表。 这些值可以是 1-31 之间的任何值。
我对该字段(DateOfMonth)的结构是:
type Subscription struct {
gorm.Model
Enabled bool `gorm:"DEFAULT:True"`
Deleted bool `gorm:"DEFAULT:False"`
UserID uint `gorm:"not null"`
Cap int `gorm:"DEFAULT:-1"`
DateOfMonth []int64 `gorm:"type:json default '[]'::json"`
}
现在,我需要在 API 中读取此值并将其与 current_date 进行比较。
为此,我尝试过:
type Result struct {
ID uint
Email string
UniqueIdentifier string
Cap int
DateOfMonth []uint8
}
var subscriptions []Result
if err := db.Table("users").Select("users.id, users.email, users.unique_identifier, subscriptions.cap, subscriptions.date_of_month").Joins("join subscriptions on users.id = subscriptions.user_id").Where("subscriptions.subscription_type_id=? and users.is_verified=? and subscriptions.enabled=?", subscription_type_id, true, true).Find(&subscriptions).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": true, "reason": "Subscribers not found!", "code": http.StatusBadRequest, "status": "failure"})
return
}
如果我将DateOfMonth []uint8
更改为DateOfMonth []int64
,则会出现错误。 我在该字段中收到的值是字节值列表 例如,[] -> [91 93] 和 [6] -> [91 54 93]
如果我这样做, bytes.NewBuffer(s.DateOfMonth)
,我会得到正确的值,但是我需要遍历这个切片以将它与今天的日期进行比较。 我尝试了很多方法来获取循环中的实际值(6)(dom值),但无济于事。
// if len(s.DateOfMonth) > 0 {
// // date_of_month_new := binary.BigEndian.Uint64(date_of_month)
// todays_date_of_month := time.Now().Day()
// fmt.Println(todays_date_of_month) //, date_of_month, reflect.TypeOf(date_of_month))
// for _, dom := range s.DateOfMonth {
// fmt.Println("help", reflect.TypeOf(dom), dom, todays_date_of_month)
// // if dom == todays_date_of_month {
// // fmt.Println("matching", dom, todays_date_of_month)
// // }
// }
// }
我在这里想念什么? 您的帮助将不胜感激。
我得到的一些错误:
invalid sql type DateOfMonth (slice) for postgres
Golang cannot range over pointer to slice
cannot range over bytes.NewBuffer(s.DateOfMonth) (type *bytes.Buffer)
sql: Scan error on column index 4, name "date_of_month": unsupported Scan, storing driver.Value type []uint8 into type *[]int
Golang cannot range over pointer to slice
您正在迭代指向切片的指针,而不是切片。 这意味着您必须首先取消引用您的变量,然后对其进行循环。 看看这个例子。
cannot range over bytes.NewBuffer(s.DateOfMonth) (type *bytes.Buffer)
您不能覆盖类型*bytes.Buffer
。 您可以改为使用Buffer.Bytes()
方法访问该类型的字节。 看看这个例子。
sql: Scan error on column index 4, name "date_of_month": unsupported Scan, storing driver.Value type []uint8 into type *[]int
从错误来看,我猜当您在扫描DateOfMonth
时使用 type []int64
时会发生这种情况。 此错误的一种可能性是您的数据库将值存储为[]uint8
而不是[]int64
。
postgres 的无效 sql 类型 DateOfMonth(切片)
成功重现此错误后,我将尝试更新我的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.