第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

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

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

Go
九州編程 2022-08-01 18:44:59
我正在使用gorm,并且我有這個結(jié)構(gòu),其中表包含一個外鍵引用,然后引用。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"`   }照片中解釋的關(guān)系:現(xiàn)在,當我使用以下命令返回用戶時:  db.Model(&user).Where().First()  // or Find()我得到地址,和國家空,像這樣:   {    ID: 1,    AddressID: 2,    Address: {          // empty address.      }   }我確實為我創(chuàng)建了重新填充和記錄的函數(shù),類似于以下內(nèi)容:AddressCountryfunc PopulateUser(user) User {   addr = FindAddresByID(user.ID)   cntr = FindCountryByCode(addr.Code)   addr.Country = cntr   user.Address = addr   return user}但我的問題:有沒有一個函數(shù)可以在不創(chuàng)建函數(shù)的情況下為我做到這一點?Gorm在這種情況下,協(xié)會可以提供幫助嗎?如果我希望在用戶刪除時刪除地址,我該如何執(zhí)行此操作?Gorm我試圖自己找到答案,但文檔有點亂。
查看完整描述

1 回答

?
守候你守候我

TA貢獻1802條經(jīng)驗 獲得超10個贊

文檔顯示了要轉(zhuǎn)到結(jié)構(gòu)引用的外鍵標記。即,在您的情況下,這些應(yīng)該在地址和國家/地區(qū),而不是地址ID和國家/地區(qū)代碼。像這樣:


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)

您可以在列上使用級聯(lián)標記。

type User struct {

  gorm.Model

  Name      string

  CompanyID int

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

}


查看完整回答
反對 回復(fù) 2022-08-01
  • 1 回答
  • 0 關(guān)注
  • 107 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號