検索
ホームページバックエンド開発Golanggolang GORMとGinは関連付けのあるオブジェクトを作成できません

golang GORM和Gin无法创建具有关联的对象

问题内容

我使用 GORM 作为 ORM 以及我的 Golang API 来与我的数据库进行通信。

但是对于创建与数据库关联的实体,代码失败了(DB.Create(&data)):

<code>2023/11/01 20:44:14 [Recovery] 2023/11/01 - 20:44:14 panic recovered:
POST /v1/product/products HTTP/1.1
Host: localhost:8080
Accept: */*
Content-Length: 589
Content-Type: application/json
User-Agent: curl/8.4.0


runtime error: invalid memory address or nil pointer dereference
/usr/lib/go/src/runtime/panic.go:261 (0x452d97)
        panicmem: panic(memoryError)
/usr/lib/go/src/runtime/signal_unix.go:861 (0x452d65)
        sigpanic: panicmem()
/home/grimm/go/pkg/mod/gorm.io/[email&#160;protected]/finisher_api.go:18 (0x926e7c)
        (*DB).Create: if db.CreateBatchSize > 0 {
/home/grimm/Documents/beeskill/website/back_end/API_website/main.go:122 (0x99cfab)
        CreatingProduct: DB.Create(&data)
/home/grimm/go/pkg/mod/github.com/gin-gonic/[email&#160;protected]/context.go:174 (0x8c9ad9)
        (*Context).Next: c.handlers[c.index](c)
/home/grimm/go/pkg/mod/github.com/gin-gonic/[email&#160;protected]/recovery.go:102 (0x8c9ac7)
        CustomRecoveryWithWriter.func1: c.Next()
/home/grimm/go/pkg/mod/github.com/gin-gonic/[email&#160;protected]/context.go:174 (0x8c8c7d)
        (*Context).Next: c.handlers[c.index](c)
/home/grimm/go/pkg/mod/github.com/gin-gonic/[email&#160;protected]/logger.go:240 (0x8c8c4c)
        LoggerWithConfig.func1: c.Next()
/home/grimm/go/pkg/mod/github.com/gin-gonic/[email&#160;protected]/context.go:174 (0x8c7d3a)
        (*Context).Next: c.handlers[c.index](c)
/home/grimm/go/pkg/mod/github.com/gin-gonic/[email&#160;protected]/gin.go:620 (0x8c79cd)
        (*Engine).handleHTTPRequest: c.Next()
/home/grimm/go/pkg/mod/github.com/gin-gonic/[email&#160;protected]/gin.go:576 (0x8c74fc)
        (*Engine).ServeHTTP: engine.handleHTTPRequest(c)
/usr/lib/go/src/net/http/server.go:2938 (0x6a35ed)
        serverHandler.ServeHTTP: handler.ServeHTTP(rw, req)
/usr/lib/go/src/net/http/server.go:2009 (0x69f4d3)
        (*conn).serve: serverHandler{c.server}.ServeHTTP(w, w.req)
/usr/lib/go/src/runtime/asm_amd64.s:1650 (0x46ed20)
        goexit: BYTE    $0x90   // NOP
</code>

使用的代码:

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
    "gorm.io/driver/sqlite"
    "gorm.io/gorm"
)

type CategoryProduct struct {
    gorm.Model
    Title       string `json:"title" gorm:"not null"`
    Description string `json:"description"`
}

type CreateCategoryProduct struct {
    gorm.Model
    Title       string `json:"title" binding:"required"`
    Description string `json:"description" binding:"required"`
}

// --------------------------------------------------------
// --------------------------------------------------------
// --------------------------------------------------------
// --------------------------------------------------------
// --------------------------------------------------------
type PriceYearProduct struct {
    gorm.Model
    Price       float64 `json:"price" gorm:"not null"`
    Description string  `json:"description"`
}

type CreatePriceYearProduct struct {
    gorm.Model
    Price       float64 `json:"price" binding:"required"`
    Description string  `json:"description" binding:"required"`
}

// --------------------------------------------------------
// --------------------------------------------------------
// --------------------------------------------------------
// --------------------------------------------------------
// --------------------------------------------------------
type PriceMounthProduct struct {
    gorm.Model
    Price       float64 `json:"price" gorm:"not null"`
    Description string  `json:"description"`
}

type CreatePriceMounthProduct struct {
    gorm.Model
    Price       float64 `json:"price" binding:"required"`
    Description string  `json:"description" binding:"required"`
}

// --------------------------------------------------------
// --------------------------------------------------------
// --------------------------------------------------------
// --------------------------------------------------------
// --------------------------------------------------------
type Product struct {
    gorm.Model
    Name               string             `json:"name" gorm:"not null"`
    Description        string             `json:"description" gorm:"not null"`
    PriceMounthProduct PriceMounthProduct `json:"pricemounth"`
    PriceYearProduct   PriceYearProduct   `json:"priceyear"`
    CategoryProduct    CategoryProduct    `json:"category"`
}

type CreateProduct struct {
    gorm.Model
    Name               string             `json:"name" binding:"required"`
    Description        string             `json:"description" binding:"required"`
    PriceMounthProduct PriceMounthProduct `json:"pricemounth" binding:"required"`
    PriceYearProduct   PriceYearProduct   `json:"priceyear" binding:"required"`
    CategoryProduct    CategoryProduct    `json:"category" binding:"required"`
}

var DB *gorm.DB

func ConnectDatabase() {

    database, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})

    if err != nil {
        panic("Failed to connect to database!")
    }
    // For the product and dependancies of them
    err = database.AutoMigrate(&CategoryProduct{}, &PriceYearProduct{}, &PriceMounthProduct{})
    if err != nil {
        return
    }
    err = database.AutoMigrate(&Product{})
    if err != nil {
        return
    }

    DB = database
}

// POST /v1/products
// Create a product
func CreatingProduct(c *gin.Context) {
    // Validate input
    var input CreateProduct
    if err := c.ShouldBindJSON(&input); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    data := Product{
        Name:               input.Name,
        Description:        input.Description,
        PriceYearProduct:   input.PriceYearProduct,
        PriceMounthProduct: input.PriceMounthProduct,
        CategoryProduct:    input.CategoryProduct,
    }
    DB.Create(&data)

    c.JSON(http.StatusOK, gin.H{"data": data})

}

func Routes() {
    var router = gin.Default()

    v1 := router.Group("/v1")
    {
        //Product CRUD
        product := v1.Group("/product")
        product.POST("/products", CreatingProduct)

    }

    err := router.Run(":8080")
    if err != nil {
        return
    }
}

func main() {
    ConnectDatabase()
    Routes()

}

以及用于发布一些数据的curl命令:

curl http://localhost:8080/v1/product/products --request "POST" --header "Content-Type: application/json" --data @file.json

file.json 的内容:

<code>{
    "name": "airplane simulation",
    "description": "airplane simulation for everybody, childrens to adults.",
    "priceyear": {
      "price": 44.99,
      "description": "pay for a year to access on irplane simulation for everybody, childrens to adults."
    },
    "pricemounth": {
      "price": 4.99,
      "description": "pay for a mounth to access on irplane simulation for everybody, childrens to adults."
    },
    "category": {
      "title": "Airplane",
      "description": "Information cataegorized on airplane."
    }
}
</code>

我查看了官方文档,但没有更多信息...... 尝试使用创建时的变量进行调试,但一切似乎都很好......

解决方法

运行代码出现错误

[error] invalid field found for struct
 main.Product's field PriceMounthProduct: 
define a valid foreign key for 
relations or implement the Valuer/Scanner interface

gin日志前第一行的错误信息,可能你错过了。

所以修复它,在 Product 结构中添加正确的 foreignkey gorm 标签 就可以了。

<code>
type Product struct {
    gorm.Model
    Name               string             `json:"name" gorm:"not null"`
    Description        string             `json:"description" gorm:"not null"`
    PriceMounthProduct PriceMounthProduct `json:"pricemounth" gorm:"foreignkey:ID"`
    PriceYearProduct   PriceYearProduct   `json:"priceyear" gorm:"foreignkey:ID"`
    CategoryProduct    CategoryProduct    `json:"category" gorm:"foreignkey:ID"`
}
</code>

然后运行

curl http://localhost:8080/v1/product/products --request "POST" --header "Content-Type: application/json" --data @info.json

得到了

<code>{"data":{"ID":1,"CreatedAt":"2023-11-02T13:37:24.052228+08:00","UpdatedAt":"2023-11-02T13:37:24.052228+08:00","DeletedAt":null,"name":"airplane simulation","description":"airplane simulation for everybody, childrens to adults.","pricemounth":{"ID":1,"CreatedAt":"2023-11-02T13:37:24.054792+08:00","UpdatedAt":"2023-11-02T13:37:24.054792+08:00","DeletedAt":null,"price":4.99,"description":"pay for a mounth to access on irplane simulation for everybody, childrens to adults."},"priceyear":{"ID":1,"CreatedAt":"2023-11-02T13:37:24.056352+08:00","UpdatedAt":"2023-11-02T13:37:24.056352+08:00","DeletedAt":null,"price":44.99,"description":"pay for a year to access on irplane simulation for everybody, childrens to adults."},"category":{"ID":1,"CreatedAt":"2023-11-02T13:37:24.056585+08:00","UpdatedAt":"2023-11-02T13:37:24.056585+08:00","DeletedAt":null,"title":"Airplane","description":"Information cataegorized on airplane."}}}% 
</code>

以上がgolang GORMとGinは関連付けのあるオブジェクトを作成できませんの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事はstackoverflowで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。
GolangとPythonの選択:プロジェクトに適していますGolangとPythonの選択:プロジェクトに適していますApr 19, 2025 am 12:21 AM

golangisidealforporformance-criticalapplicationsandconcurrentprogramming、whilepythonexcelsindatascience、rapyプロトタイプ、およびandversitielity.1)for-high-duetoitsefficiency and concurrencyfeatures.2

Golang:並行性と行動のパフォーマンスGolang:並行性と行動のパフォーマンスApr 19, 2025 am 12:20 AM

GolangはGoroutineとChannelを通じて効率的な並行性を実現します。1。Goroutineは、Goキーワードで始まる軽量のスレッドです。 2.チャンネルは、ゴルチン間の安全な通信に使用され、人種の状態を避けます。 3.使用例は、基本的および高度な使用法を示しています。 4.一般的なエラーには、ゴルンレースで検出できるデッドロックとデータ競争が含まれます。 5.パフォーマンスの最適化では、チャネルの使用を削減し、ゴルチンの数を合理的に設定し、Sync.poolを使用してメモリを管理することを示唆しています。

Golang vs. Python:どの言語を学ぶべきですか?Golang vs. Python:どの言語を学ぶべきですか?Apr 19, 2025 am 12:20 AM

Golangは、システムプログラミングと高い並行性アプリケーションにより適していますが、Pythonはデータサイエンスと迅速な発展により適しています。 1)GolangはGoogleによって開発され、静的にタイピングし、シンプルさと効率を強調しており、高い並行性シナリオに適しています。 2)Pythonは、Guidovan Rossumによって作成され、動的に型付けられた簡潔な構文、幅広いアプリケーション、初心者やデータ処理に適しています。

Golang vs. Python:パフォーマンスとスケーラビリティGolang vs. Python:パフォーマンスとスケーラビリティApr 19, 2025 am 12:18 AM

Golangは、パフォーマンスとスケーラビリティの点でPythonよりも優れています。 1)Golangのコンピレーションタイプの特性と効率的な並行性モデルにより、高い並行性シナリオでうまく機能します。 2)Pythonは解釈された言語として、ゆっくりと実行されますが、Cythonなどのツールを介してパフォーマンスを最適化できます。

Golang vs.その他の言語:比較Golang vs.その他の言語:比較Apr 19, 2025 am 12:11 AM

GO言語は、同時プログラミング、パフォーマンス、学習曲線などにユニークな利点を持っています。1。GoroutineとChannelを通じて同時プログラミングが実現されます。これは軽量で効率的です。 2。コンピレーション速度は高速で、操作性能はC言語のパフォーマンスに近いです。 3.文法は簡潔で、学習曲線は滑らかで、生態系は豊富です。

Golang and Python:違いを理解するGolang and Python:違いを理解するApr 18, 2025 am 12:21 AM

GolangとPythonの主な違いは、並行性モデル、タイプシステム、パフォーマンス、実行速度です。 1. GolangはCSPモデルを使用します。これは、同時タスクの高いタスクに適しています。 Pythonは、I/O集約型タスクに適したマルチスレッドとGILに依存しています。 2。Golangは静的なタイプで、Pythonは動的なタイプです。 3.ゴーランコンパイルされた言語実行速度は高速であり、Python解釈言語開発は高速です。

Golang vs. C:速度差の評価Golang vs. C:速度差の評価Apr 18, 2025 am 12:20 AM

Golangは通常Cよりも遅くなりますが、Golangはプログラミングと開発効率の同時により多くの利点があります。1)Golangのゴミ収集と並行性モデルにより、同時性の高いシナリオではうまく機能します。 2)Cは、手動のメモリ管理とハードウェアの最適化により、より高いパフォーマンスを取得しますが、開発の複雑さが高くなります。

Golang:クラウドコンピューティングとDevOpsのキー言語Golang:クラウドコンピューティングとDevOpsのキー言語Apr 18, 2025 am 12:18 AM

GolangはクラウドコンピューティングとDevOpsで広く使用されており、その利点はシンプルさ、効率性、および同時プログラミング機能にあります。 1)クラウドコンピューティングでは、GolangはGoroutineおよびチャネルメカニズムを介して同時リクエストを効率的に処理します。 2)DevOpsでは、Golangの高速コンピレーションとクロスプラットフォーム機能により、自動化ツールの最初の選択肢になります。

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

EditPlus 中国語クラック版

EditPlus 中国語クラック版

サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

AtomエディタMac版ダウンロード

AtomエディタMac版ダウンロード

最も人気のあるオープンソースエディター

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境