Golang's gorm defines a field to hold the picture list question

golang"s gorm defines a field to save the picture list question:

type Article struct {
    BaseModel
    Title       string     `json:"title" gorm:"type:varchar(64);not null"`
    Content     string     `json:"content"  gorm:"type:text;not null"`
    Status      uint8      `json:"status"`
    Pics1       string     `json:"pics" gorm:"type:json" `
    Pics2       string     `json:"pics" gorm:"type:text" `
}

question:
as shown in the above code, an article may have several pictures, and the image file names are saved in the json array (using mysql8.0), so:
1, what does the Pic field type write? If the string, written above is changed to json, an error will be reported.
2. What does the type of gorm write? Json or text??

Jan.08,2022

two methods:

  1. if the database field is json, then set gorm to interface, but take it out to make assertions (JSON has both interface {} and map)
  2. if the database is text, then gorm is set to string,. Similarly, type assertions are required when parsing

Don't bother. I think a better solution is to store the json serialized data of an array or map as the specific type of string,. When using it, it is more convenient to deserialize it.

Menu