【问题标题】:table references a table which in turn references another table表引用一个表,该表又引用另一个表
【发布时间】:2021-05-01 17:15:08
【问题描述】:

我正在使用 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中做到这一点?

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

【问题讨论】:

    标签: mysql go go-gorm


    【解决方案1】:

    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;"`
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-06
      • 1970-01-01
      • 1970-01-01
      • 2018-04-02
      • 2018-01-03
      • 2011-01-11
      • 2012-02-27
      • 1970-01-01
      相关资源
      最近更新 更多