Gorm users face an obstacle while attempting to store an array of integers within a single field of a PostgresQL database using the framework. The error message, "panic: invalid sql type (slice) for postgres," arises due to the default mismatch between Gorm's slice data type and PostgresQL's native array support.
To address this issue effectively, it is necessary to employ custom types provided by the underlying database library. In this case, the pq package offers the pq.Int64Array type, which natively supports PostgresQL arrays. The following code exemplifies the proper usage:
<code class="go">type Game struct { gorm.Model GameCode string GameName string DeckType pq.Int64Array `gorm:"type:integer[]"` GameEndDate string }</code>
Where Game.DeckType specifies the type using the gorm:"type:integer[]" tag, effectively defining it as an array of integers within the PostgresQL database.
After establishing the custom type, you can effortlessly insert an array of integers into the database:
<code class="go">dt := []int64{1, 2, 3} db.Create(&Game{GameCode: "xxx", GameName: "xxx", DeckType: pq.Int64Array(dt), GameEndDate: "xxx"})</code>
This code creates a new record in the Game table, where DeckType is stored as an array of integers.
The above is the detailed content of How to Store an Array of Integers as a Gorm Model Data Type in PostgresQL?. For more information, please follow other related articles on the PHP Chinese website!