How to store an array of integers as a single field in a PostgreSQL database using Gorm?

Susan Sarandon
Release: 2024-11-04 16:54:02
Original
962 people have browsed it

How to store an array of integers as a single field in a PostgreSQL database using Gorm?

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>
Copy after login

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(&amp;Game{GameCode: "xxx", GameName: "xxx", DeckType: pq.Int64Array(dt), GameEndDate: "xxx"})</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!