Adding an Array of Integers as a Data Type in Gorm Model
When dealing with database models, it's often necessary to store arrays of values. In Gorm, the official ORM for Go, saving an array of integers as a single field in PostgreSQL can be a challenge.
To address this issue, Gorm provides support for handling arrays by using custom types from the underlying library. By leveraging the pq library, you can define an array type within your model.
For example, consider the following updated Gorm model:
<code class="go">type Game struct { gorm.Model GameCode string GameName string DeckType pq.Int64Array `gorm:"type:integer[]"` GameEndDate string }</code>
Here, DeckType is defined as pq.Int64Array, which represents an array of integers. The gorm:"type:integer[]" tag specifies the PostgreSQL type as an integer array.
To insert a record with an array of integers, simply assign the array to the DeckType field:
<code class="go">dt := []int64{1, 2, 3} db.Create(&Game{GameCode: "xxx", GameName: "xxx", DeckType: pq.Int64Array(dt), GameEndDate: "xxx"})</code>
By using custom types from pq, you can seamlessly save and retrieve arrays of integers as a single field in your Gorm model.
The above is the detailed content of How to Store an Array of Integers as a Single Field in a Gorm Model Using PostgreSQL?. For more information, please follow other related articles on the PHP Chinese website!