SoFunction
Updated on 2025-03-03

GORM access array/custom type data in Go language

GORM access array type data

existGORMAccess to array type variable data is not supported, it can be done throughGROMcustom data type implementation.

1. Custom Types of GORM

1. Scanner/Valuer interface

GORMThe custom data type must be implementedScanner/Valuerinterface.

(1) ScannerInterfaceScanThe 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) ValuerInterfaceValueThe method is to encode the Go variable when it is stored in the database.

2. Array variables

AlthoughGORMArray variables are not supported, but can be implementedScanner/ValuerInterface, performs similar decoding/encoding processing when database fetching/memorizing, making array variables a variable type that the database can support.

(1) ImplementationSacnnerinterface

ScanFunction, 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 aboveStrsType, the underlying type is not string array.ScanThe function will readvalThe 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

ValueFunction: 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 aboveStrsBefore depositing it into the database, splice the strings in the array with "|" to obtain the database support.stringType 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/ValuerSimple use of interfaces, array types are used in actual productionConvert tojsonSave strings, a complete example is shown below,UserAs 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!