Home > Article > Backend Development > How to Persist Custom Set Data Types in GORM with Golang?
Persisting Custom Set Data Type using GORM Golang
When using a custom Set data type to define one-to-many relationships in GORM, you may encounter an error due to it being an invalid SQL type. To overcome this, you need to implement the Scanner and Driver Valuer interfaces for your custom type. This will allow the database driver to understand how to store and retrieve the data in the database.
Scanner Interface
The Scanner interface has the following method:
func (data *CustomType) Scan(value interface{}) error
This method is used to scan the value from the database into your custom type. You should implement this method to convert the database value into your custom type.
Driver Valuer Interface
The Driver Valuer interface has the following method:
func (data *CustomType) Value() (driver.Value, error)
This method is used to convert your custom type into a database value. You should implement this method to convert your custom type into a format that the database can understand.
Example
Let's consider a custom type UserAccess, which is a map[interface{}]struct{}.
type UserAccess map[interface{}]struct{} func (data *UserAccess) Value() (driver.Value, error) { return data.ConvertJSONToString(), nil } func (data *UserAccess) Scan(value interface{}) error { *data = data.ConvertStringToJson(valueString) }
In this example, ConvertStringToJson and ConvertJSONToString are helper functions that convert between UserAccess and a database-compatible format like a JSON string.
By implementing these interfaces, you're informing the database driver how to handle your custom data type, allowing you to persist it in your database.
The above is the detailed content of How to Persist Custom Set Data Types in GORM with Golang?. For more information, please follow other related articles on the PHP Chinese website!