GORM access array type data
exist
GORM
Access to array type variable data is not supported, it can be done throughGROM
custom data type implementation.
1. Custom Types of GORM
1. Scanner/Valuer interface
GORM
The custom data type must be implementedScanner
/Valuer
interface.
(1) Scanner
InterfaceScan
The method is the parsing process that needs to be performed when reading data from the database to Go variables, and the decoding process type.
(2) Valuer
InterfaceValue
The method is to encode the Go variable when it is stored in the database.
2. Array variables
AlthoughGORM
Array variables are not supported, but can be implementedScanner
/Valuer
Interface, performs similar decoding/encoding processing when database fetching/memorizing, making array variables a variable type that the database can support.
(1) ImplementationSacnner
interface
Scan
Function, after reading data from the database, process it, and then obtain a Go-type variable.
type Strs []string func (m *Strs) Scan(val interface{}) error { s := val.([]uint8) ss := (string(s), "|") *m = ss return nil }
Customize as aboveStrs
Type, the underlying type is not string array.Scan
The function will readval
The value is processed according to the string, cut with "|" as the separator, obtain the string array type, and then assign values using a pointer.
(2) Implement the Valuer interface
Value
Function: When saving data to the database, the data is processed and the database supports type.
func (m Strs) Value() (, error) { str := (m, "|") return str, nil }
As aboveStrs
Before depositing it into the database, splice the strings in the array with "|" to obtain the database support.string
Type and then save it to the database.
3. Test
Define the following function for testing
(1) Model variables
type User struct { ID uint `gorm:"primary_key"` Name string Pics Strs `gorm:"type:longtext"` // Custom array type, stored as long text type in the database}
(2) Service function
func SaveUser(user User) error { var err error err = (&user).Error return err } func GetUser(name string) (User, error) { var user User err := (&user, "name = ?", name).Error return user, err }
(3) testService function
func TestSaveUser() { user := User{ Name: "Jason", Pics: Strs{ "123124", "gtsrbxrzsfcv", }, } err := SaveUser(user) if err != nil { ("Save failed!", err) } else { ("Save successfully!") } } func TestGetUser() { user, err := GetUser("Jason") if err != nil { ("Failed to obtain!", err) } else { ("Get successful!", user) } }
(4) Operation results
2022/07/30 18:18:41 Save successfully!
2022/07/30 18:18:41 Successfully obtained! {3 Jason [123124 gtsrbxrzsfcv]}
In database storage, it is reflected as:
mysql> select *from users; +----+-------+---------------------+ | id | name | pics | +----+-------+---------------------+ | 3 | Jason | 123124|gtsrbxrzsfcv | +----+-------+---------------------+ 1 row in set (0.00 sec)
2. Actual production
The example above showsScanner
/Valuer
Simple use of interfaces, array types are used in actual productionConvert tojson
Save strings, a complete example is shown below,User
As an example, having a bank card containing information (of course, it can be achieved through one-to-one association 4444).
(1) Implement custom types
type User struct { ID uint `gorm:"primary_key"` Name string Cards Card `gorm:"json"` } type Card struct { // Specify the tag of json. Type int `json:"type"` Account string `json:"account"` Password string `json:"password"` } // Scan decodes json stringfunc (card *Card) Scan(val interface{}) error { b, _ := val.([]byte) return (b, card) } // Value encoding jsonfunc (card Card) Value() (value , err error) { return (card) }
(2) Data table model
type User struct { ID uint `gorm:"primary_key"` Name string Cards Card `gorm:"json"` // Specify as json type}
Summary
This is the article about GORM access array/custom type data in Go language. For more related GORM access arrays, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!