根據php小編香蕉的介紹,GORM是一款流行的Go語言ORM庫,它提供了便捷的資料庫操作方式。然而,GORM並不支援所有的資料類型,並且在處理某些資料類型時可能會出現錯誤的架構。這意味著在使用GORM時,開發者需要注意使用支援的資料類型,並確保資料架構正確,以避免潛在的問題。雖然GORM功能強大,但這些限制需要開發者在使用時謹慎處理。
問題內容
gorm v1.25.1,我嘗試在worker
、poster
和job
模型上執行db.automigrate()
,但遇到[錯誤] 不支援的資料類型:&[]
。 worker 和 job 結構應該有 many-to-many 關係
,而 poster 和 job 應該有 one-to-many
關係。工人和經驗、工人和偏好都應該是 one-to-many
關係。請幫忙。
package model type experience struct { gorm.Model Company int `json:"company"` JobTitle string `json:"jobTitle"` WorkerID uint } type preference struct { gorm.Model JobTitle string `json:"JobTitle"` MinPay int `json:"minPay"` MaxPay int `json:"maxPay"` WorkerID uint } type Worker struct { gorm.Model Username string `gorm:"uniqueIndex;not null" json:"username"` ...more fields Experience []experience `json:"experience"` Preference []preference `json:"preference"` AppliedJobs []Job `gorm:"many2many:worker_jobs;" json:"appliedJobs"` } type Poster struct { gorm.Model Name string `gorm:"uniqueIndex;not null" json:"name"` Email string `gorm:"uniqueIndex;not null" json:"email"` Phone string `json:"phone"` JobsPosted []Job `json:"jobsPosted"` } type Job struct { gorm.Model Title string `gorm:"uniqueIndex;not null" json:"title"` ...more fields PosterID uint `json:"posterID"` }
解決方法
我能夠透過以下程式碼實現您所需要的。
請注意,為了演示,我透過僅包含關聯的相關欄位來簡化您的模型(結構)。如果我遺漏了一些值得一提的內容,請隨時詢問,我會更新我的答案。
我先分享一下程式碼,然後再詳細解釋。
package main import ( "gorm.io/driver/postgres" "gorm.io/gorm" ) type Worker struct { gorm.Model Username string `gorm:"uniqueIndex;not null" json:"username"` Posters []Poster `gorm:"many2many:workers_posters;joinForeignKey:postersId"` } type Poster struct { gorm.Model Name string `gorm:"uniqueIndex;not null" json:"name"` Email string `gorm:"uniqueIndex;not null" json:"email"` Phone string `json:"phone"` Workers []Worker `gorm:"many2many:workers_posters;joinForeignKey:workersId"` Jobs []Job } type Job struct { gorm.Model Title string `gorm:"uniqueIndex;not null" json:"title"` PosterID uint `json:"posterID"` } func main() { dsn := "host=localhost port=54322 user=postgres password=postgres dbname=postgres sslmode=disable" db, err := gorm.Open(postgres.Open(dsn)) if err != nil { panic(err) } db.AutoMigrate(&Worker{}, &Poster{}, &Job{}) }
由於您的問題同時涉及 many2many
和 one2many
關係,因此我將把我的答案分為兩部分。
many2many
關係
要實現這種關係,您必須在保存關聯實體的切片旁邊添加註釋 gorm:"many2many:workers_posters;joinforeignkey:workersid"
。受影響的欄位是:
-
posters
結構體中的worker
欄位 -
workers
結構體中的poster
欄位
顯然,您必須根據要設定的欄位變更 joinforeignkey
的值。
one2many
關係
這種關係甚至更簡單,因為您不必指定必須在 many2many
關聯中建立的聯接表(例如上面建立的 workers_posters
表)。在這裡,您只需要做這兩個更改:
- 在
poster
結構中新增jobs []job
欄位 - 在
job
結構中新增posterid uint
欄位
因此,如果您執行 automigrate
方法,您將在資料庫中看到正確的表,並且所有外鍵都已正確設定。
請告訴我,謝謝!
以上是GORM 不支援的資料類型:&、不正確的架構的詳細內容。更多資訊請關注PHP中文網其他相關文章!

goisastrongchoiceforprojectsneedingsimplicity,績效和引發性,butitmaylackinadvancedfeatures and ecosystemmaturity.1)

Go'sinitfunctionandJava'sstaticinitializersbothservetosetupenvironmentsbeforethemainfunction,buttheydifferinexecutionandcontrol.Go'sinitissimpleandautomatic,suitableforbasicsetupsbutcanleadtocomplexityifoverused.Java'sstaticinitializersoffermorecontr

thecommonusecasesfortheinitfunctionoare:1)加載configurationfilesbeforeThemainProgramStarts,2)初始化的globalvariables和3)runningpre-checkSorvalidationsbeforEtheprofforeTheProgrecce.TheInitFunctionIsautefunctionIsautomentycalomationalmatomatimationalycalmatemationalcalledbebeforethemainfuniinfuninfuntuntion

ChannelsarecrucialingoforenablingsafeandefficityCommunicationBetnewengoroutines.theyfacilitateSynChronizationAndManageGoroutIneLifeCycle,EssentialforConcurrentProgramming.ChannelSallSallSallSallSallowSallowsAllowsEnderDendingAndReceivingValues,ActassignalsignalsforsynChronization,and actassignalsynChronization and andsupppor

在Go中,可以通過errors.Wrap和errors.Unwrap方法來包裝錯誤並添加上下文。 1)使用errors包的新功能,可以在錯誤傳播過程中添加上下文信息。 2)通過fmt.Errorf和%w包裝錯誤,幫助定位問題。 3)自定義錯誤類型可以創建更具語義化的錯誤,增強錯誤處理的表達能力。

Gooffersrobustfeaturesforsecurecoding,butdevelopersmustimplementsecuritybestpracticeseffectively.1)UseGo'scryptopackageforsecuredatahandling.2)Manageconcurrencywithsynchronizationprimitivestopreventraceconditions.3)SanitizeexternalinputstoavoidSQLinj

Go的錯誤接口定義為typeerrorinterface{Error()string},允許任何實現Error()方法的類型被視為錯誤。使用步驟如下:1.基本檢查和記錄錯誤,例如iferr!=nil{log.Printf("Anerroroccurred:%v",err)return}。 2.創建自定義錯誤類型以提供更多信息,如typeMyErrorstruct{MsgstringDetailstring}。 3.使用錯誤包裝(自Go1.13起)來添加上下文而不丟失原始錯誤信息,

對效率的Handleerrorsinconcurrentgopragrs,UsechannelstocommunicateErrors,enplionErrorWatchers,Instertimeout,UsebufferedChannels和Provideclearrormessages.1)USEchannelelStopassErtopassErrorsErtopassErrorsErrorsErrorsFromGoroutInestOthemainFunction.2)


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

WebStorm Mac版
好用的JavaScript開發工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

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

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器