登录
首页 >  Golang >  Go问答

表嵌套表的引用

来源:stackoverflow

时间:2024-02-14 15:54:23 384浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《表嵌套表的引用》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

问题内容

我正在使用 gorm,并且我有这样的结构,其中 user 表包含引用 address 的外键,然后该外键引用 country

   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.
      }

   }

我确实为我创建了重新填充 addresscountry 记录的函数,类似于:

func PopulateUser(user) User {

   addr = FindAddresByID(user.ID)
   cntr = FindCountryByCode(addr.Code)

   addr.Country = cntr
   user.Address = addr

   return user

}

但是我的问题:

  1. gorm 中是否有一个函数可以为我执行此操作,而无需我创建该函数?
  2. 在这种情况下协会可以提供帮助吗?
  3. 如果我希望在用户删除时删除该地址,我该如何在 gorm 中执行此操作?

我尝试自己寻找答案,但文档有点混乱。


解决方案


documentation 显示了结构引用的外键标记。 即在您的情况下,这些应该位于地址和国家/地区,而不是地址 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"`
   }

请尝试使用这些。

对于

  1. 请参阅急切加载 here
db.preload("user").preload("address").find(&users)
  1. 您可以在该列上使用 cascade 标签。
type User struct {
  gorm.Model
  Name      string
  CompanyID int
  Company   Company `gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
}

今天关于《表嵌套表的引用》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>