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 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 protected]/context.go:174 (0x8c9ad9) (*Context).Next: c.handlers[c.index](c) /home/grimm/go/pkg/mod/github.com/gin-gonic/[email protected]/recovery.go:102 (0x8c9ac7) CustomRecoveryWithWriter.func1: c.Next() /home/grimm/go/pkg/mod/github.com/gin-gonic/[email protected]/context.go:174 (0x8c8c7d) (*Context).Next: c.handlers[c.index](c) /home/grimm/go/pkg/mod/github.com/gin-gonic/[email protected]/logger.go:240 (0x8c8c4c) LoggerWithConfig.func1: c.Next() /home/grimm/go/pkg/mod/github.com/gin-gonic/[email protected]/context.go:174 (0x8c7d3a) (*Context).Next: c.handlers[c.index](c) /home/grimm/go/pkg/mod/github.com/gin-gonic/[email protected]/gin.go:620 (0x8c79cd) (*Engine).handleHTTPRequest: c.Next() /home/grimm/go/pkg/mod/github.com/gin-gonic/[email 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中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

OpenSSL,作為廣泛應用於安全通信的開源庫,提供了加密算法、密鑰和證書管理等功能。然而,其歷史版本中存在一些已知安全漏洞,其中一些危害極大。本文將重點介紹Debian系統中OpenSSL的常見漏洞及應對措施。 DebianOpenSSL已知漏洞:OpenSSL曾出現過多個嚴重漏洞,例如:心臟出血漏洞(CVE-2014-0160):該漏洞影響OpenSSL1.0.1至1.0.1f以及1.0.2至1.0.2beta版本。攻擊者可利用此漏洞未經授權讀取服務器上的敏感信息,包括加密密鑰等。

後端學習路徑:從前端轉型到後端的探索之旅作為一名從前端開發轉型的後端初學者,你已經有了nodejs的基礎,...

在BeegoORM框架下,如何指定模型關聯的數據庫?許多Beego項目需要同時操作多個數據庫。當使用Beego...

Go語言中用於浮點數運算的庫介紹在Go語言(也稱為Golang)中,進行浮點數的加減乘除運算時,如何確保精度是�...

Go爬蟲Colly中的Queue線程問題探討在使用Go語言的Colly爬蟲庫時,開發者常常會遇到關於線程和請求隊列的問題。 �...

Go語言中使用RedisStream實現消息隊列時類型轉換問題在使用Go語言與Redis...

Go語言中字符串打印的區別:使用Println與string()函數的效果差異在Go...

GoLand中自定義結構體標籤不顯示怎麼辦?在使用GoLand進行Go語言開發時,很多開發者會遇到自定義結構體標籤在�...
