Home > Backend Development > Golang > How to Store an Array of Integers as a Single Field in a Gorm Model Using PostgreSQL?

How to Store an Array of Integers as a Single Field in a Gorm Model Using PostgreSQL?

Susan Sarandon
Release: 2024-11-04 11:00:01
Original
978 people have browsed it

How to Store an Array of Integers as a Single Field in a Gorm Model Using PostgreSQL?

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

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

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!

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