Adding an Array of Integers as a Data Type in a Gorm Model
When attempting to save an array of numbers as a single field in a Postgres database using Gorm, users may encounter an error indicating an invalid SQL type. To resolve this issue, custom types from the underlying library should be used.
The following code snippet demonstrates how to declare a Gorm model with an array of integers as a data type:
<code class="go">type Game struct { gorm.Model GameCode string GameName string DeckType pq.Int64Array `gorm:"type:integer[]"` // Use custom type from pq library GameEndDate string }</code>
To add records to the database using this model, create an array of integers and use the Create method:
<code class="go">dt := []int64{1, 2, 3} db.Create(&Game{GameCode: "xxx", GameName: "xxx", DeckType: pq.Int64Array(dt), GameEndDate: "xxx"})</code>
By employing custom types, you can effectively work with arrays of integers as data types in your Gorm models when interacting with a Postgres database.
The above is the detailed content of How to store an array of integers as a single field in a PostgreSQL database using Gorm?. For more information, please follow other related articles on the PHP Chinese website!