We know that Gorm does not support elements of array type, but in PgSQL, array types are supported.

So how do you get Gorm to support this type at this point?

Using arrays directly

So let’s say we have a Model like this

type Product struct {
	gorm.Model
	Code string `json:"code"`
	Price uint `json:"price"`
	Names [] `json:"names" gorm:"type:varchar(100)[]"`
}
Copy the code

And start the PG database in this way

db, err := gorm.Open("postgres"."host=localhost port=5433 user=postgres dbname=gorm sslmode=disable password=**")
	iferr ! =nil {
		panic(err)
	}
	db.AutoMigrate(&model.Product{})
Copy the code

So, when we start up, GORm will report an error saying that this mode is not supported

Use lib/pg

In an issue of GORM, I found a solution for this, which is to use “github.com/lib/pq”

Let’s import the latest “github.com/lib/pq”

And change the Product struct above to

type Product struct {
	gorm.Model
	Code string `json:"code"`
	Price uint `json:"price"`
	Names  pq.StringArray `json:"names" gorm:"type:varchar(100)[]"`
}
Copy the code

It is ok