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

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

DDD
Release: 2024-11-05 14:49:02
Original
239 people have browsed it

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

Adding an Array of Integers as a Data Type in a Gorm Model

Introduction:
When working with PostgreSQL using Gorm, adding an array of integers as a data type in a model can present challenges. This article addresses a common issue encountered when attempting such an operation.

Problem:
Gorm models often encounter an error when trying to save an array of numbers in a single PostgreSQL field. The error typically reads, "panic: invalid sql type (slice) for postgres."

Troubleshooting:
The issue arises from using the slice as a data type. The solution involves utilizing custom types from the underlying PostgreSQL driver library.

Solution:
In the provided model:

<code class="go">type Game struct {
    gorm.Model
    GameCode    string
    GameName    string
    DeckType    pq.Int64Array
    GameEndDate string
}</code>
Copy after login

Replace DeckType []int64 with DeckType pq.Int64Array, where pq is imported as import pq "github.com/lib/pq".

GORM Tag:
To properly map the custom type to the database column, add a gorm tag to specify the column type:

<code class="go">DeckType    pq.Int64Array `gorm:"type:integer[]"`</code>
Copy after login

This tag denotes that the DeckType field should be mapped to a PostgreSQL integer array.

Example Insertion:
After modifying the model and adding the GORM tag, you can 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

By using the custom type and GORM tag, you can successfully save an array of integers in a PostgreSQL field.

The above is the detailed content of How to Store an Array of Integers 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template