错误:列“country”的类型为text[],但表达式的类型为记录(SQLSTATE 42804)

问题描述 投票:0回答:1

作为初学者,我想知道我的代码中做错了什么,我问chatgpt,但它没有给我很好的信息。感谢任何帮助。

web-1  | 2024/03/31 14:26:43 /usr/src/app/handlers/ads.go:59 ERROR: column "country" is of type text[] but expression is of type record (SQLSTATE 42804)
web-1  | [0.248ms] [rows:0] INSERT INTO "conditions" ("created_at","updated_at","deleted_at","ad_id","age_start","age_end","gender","country","platform") VALUES ('2024-03-31 14:26:43.751','2024-03-31 14:26:43.751',NULL,5,20,30,('M'),('TW','JP'),('android','ios')) ON CONFLICT ("id") DO UPDATE SET "ad_id"="excluded"."ad_id" RETURNING "id"
package models

import (
    "time"

    "gorm.io/gorm"
)

type AD struct {
    gorm.Model
    Title      string       `json:"title" gorm:"type:text"`
    StartAt    time.Time    `json:"startAt" gorm:"type:timestamp"`
    EndAt      time.Time    `json:"endAt" gorm:"type:timestamp"`
    IsActive   bool         `gorm:"default:False;type:boolean"`
    Conditions []Conditions `json:"conditions"`
}

type Conditions struct {
    gorm.Model
    ADID     uint
    AgeStart int      `json:"ageStart" gorm:"default:0;type:integer"`
    AgeEnd   int      `json:"ageEnd" gorm:"default:100;type:integer"`
    Gender   []string `json:"gender" gorm:"type:text[]"`
    Country  []string `json:"country" gorm:"type:text[]"`
    Platform []string `json:"platform" gorm:"type:text[]"`
}
func CreateAd(c *fiber.Ctx) error {
    ad := new(models.AD)
    if err := c.BodyParser(ad); err != nil {
        return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
            "error": err.Error(),
        })
    }

    if IsAdAlive(*ad) {
        ad.IsActive = true
    } else {
        ad.IsActive = false
    }

    fmt.Println(ad)

    database.DB.Db.Model(models.AD{}).Create(&ad)
    return c.Status(200).JSON(ad)
}

我问了chatGPT,它是这样说的:

查看 GORM 文档:确保您正确使用 GORM 的功能来处理数组。 GORM 应该消除为 PostgreSQL 手动格式化数组的需要。如果 GORM 期望的数组格式与您的 PostgreSQL 版本期望的格式存在差异,这可能会导致问题。检查最新的 GORM 文档以了解阵列支持或与阵列处理相关的任何未决问题可以提供见解或解决方案。

但我找不到那些。

go orm go-gorm go-fiber
1个回答
0
投票

更改为

pq.StringArray
类型,还包括
"github.com/lib/pq"

type Conditions struct {
    gorm.Model
    ADID     uint
    AgeStart int            `json:"ageStart" gorm:"default:0;type:integer"`
    AgeEnd   int            `json:"ageEnd" gorm:"default:100;type:integer"`
    Gender   pq.StringArray `json:"gender" gorm:"type:text[]"`
    Country  pq.StringArray `json:"country" gorm:"type:text[]"`
    Platform pq.StringArray `json:"platform" gorm:"type:text[]"`
}
© www.soinside.com 2019 - 2024. All rights reserved.