亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

表引用一個表,而表又引用另一個表

表引用一個表,而表又引用另一個表

Go
九州編程 2022-08-01 18:44:59
我正在使用gorm,并且我有這個結構,其中表包含一個外鍵引用,然后引用。UserAddressCountry   type User struct {      ID              int       `gorm:"column:id; primaryKey; autoIncrement" json:"id"`      Address         Address      AddressID       int  `gorm:"column:address_id;foreignKey:AddressID;references:ID" json:"address"`   }   type Address struct {      ID          int `gorm:"column:ID;primaryKey;autoIncrement;" json:"id"`      CountryCode int `gorm:"column:country_code; foreignKey:CountryCode; references:Code" json:"country_code"`      Country     Country   }   type Country struct {      Code          int    `gorm:"column:code; primaryKey; autoIncrement" json:"code"`      Name          string `gorm:"column:name" json:"name"`      ContinentName string `gorm:"column:continent_name" json:"continentName"`   }照片中解釋的關系:現在,當我使用以下命令返回用戶時:  db.Model(&user).Where().First()  // or Find()我得到地址,和國家空,像這樣:   {    ID: 1,    AddressID: 2,    Address: {          // empty address.      }   }我確實為我創建了重新填充和記錄的函數,類似于以下內容:AddressCountryfunc PopulateUser(user) User {   addr = FindAddresByID(user.ID)   cntr = FindCountryByCode(addr.Code)   addr.Country = cntr   user.Address = addr   return user}但我的問題:有沒有一個函數可以在不創建函數的情況下為我做到這一點?Gorm在這種情況下,協會可以提供幫助嗎?如果我希望在用戶刪除時刪除地址,我該如何執行此操作?Gorm我試圖自己找到答案,但文檔有點亂。
查看完整描述

1 回答

?
守候你守候我

TA貢獻1802條經驗 獲得超10個贊

文檔顯示了要轉到結構引用的外鍵標記。即,在您的情況下,這些應該在地址和國家/地區,而不是地址ID和國家/地區代碼。像這樣:


type User struct {

      Address         Address `gorm:"foreignKey:AddressID;references:ID"`

      AddressID       int  `gorm:"column:address_id"`

   }


type Address struct {

      CountryCode int `gorm:"column:country_code"`

      Country     Country gorm:"foreignKey:CountryCode; references:Code"`

   }

請嘗試使用這些。



請在此處查看急切加載

db.Preload("User").Preload("Address").Find(&users)

您可以在列上使用級聯標記。

type User struct {

  gorm.Model

  Name      string

  CompanyID int

  Company   Company `gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`

}


查看完整回答
反對 回復 2022-08-01
  • 1 回答
  • 0 關注
  • 105 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號