Home > Backend Development > Golang > How to Store an Array of Integers as a Gorm Model Data Type in PostgresQL?

How to Store an Array of Integers as a Gorm Model Data Type in PostgresQL?

Linda Hamilton
Release: 2024-11-09 08:05:02
Original
260 people have browsed it

How to Store an Array of Integers as a Gorm Model Data Type in PostgresQL?

Integrating Array of Integers as Gorm Model Data Type

The Issue

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.

The Resolution

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

Where Game.DeckType specifies the type using the gorm:"type:integer[]" tag, effectively defining it as an array of integers within the PostgresQL database.

Example Insertion

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

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!

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