Home > Article > Backend Development > How to Store Arrays of Integers in a GORM Model Using PostgreSQL?
In the Go programming language, GORM is a popular ORM (object-relational mapper) framework for working with databases. When working with a relational database like PostgreSQL, it's often necessary to store collections of values in a single field, known as an array.
When attempting to add an array of integers []int64 to a Gorm model field, one might encounter the error: "panic: invalid sql type (slice) for postgres." This error occurs because Gorm cannot automatically map a slice to a database field.
To resolve this issue, it's necessary to use a custom data type provided by the underlying database library. In the case of PostgreSQL, the pq library offers a way to represent an integer array as a custom type pq.Int64Array for the DeckType field in the Gorm model:
<code class="go">type Game struct { gorm.Model GameCode string GameName string DeckType pq.Int64Array `gorm:"type:integer[]"` GameEndDate string }</code>
In the gorm tag, type:integer[] specifies that this field should be treated as an array of integers in the database.
To insert an array of integers into a Gorm model, one can use the following syntax:
<code class="go">dt := []int64{1, 2, 3} db.Create(&Game{GameCode: "xxx", GameName: "xxx", DeckType: pq.Int64Array(dt), GameEndDate: "xxx"}) </code>
The above is the detailed content of How to Store Arrays of Integers in a GORM Model Using PostgreSQL?. For more information, please follow other related articles on the PHP Chinese website!