代码之家  ›  专栏  ›  技术社区  ›  C0ol_Cod3r

用GoLang保存额外数据

  •  0
  • C0ol_Cod3r  · 技术社区  · 7 年前

    我有三个表/结构,Profile,Addresses和Profile\u Addresses

    简况

    type Profile struct {
      gorm.Model
      Company string `gorm:"size:255" json:"company"`
      AddedDate time.Time `gorm:"type:date" json:"date_added"`
      ProfileAddresses []ProfileAddress `gorm:"foreignkey:profile_fk" json:"address_id"`
    }
    

    type Address struct {
      gorm.Model 
      AddressLine1 string `gorm:"size:255" json:"line1"`
      AddressLine2 string `gorm:"size:255" json:"line2"`
      AddressLine3 string `gorm:"size:255" json:"line3"`
      City string `gorm:"size:200" json:"city"`
      Country string `gorm:"size:255" json:"country"`
      Postcode string `gorm:"size:12" json:"postcode"`
      ProfileAddresses []ProfileAddress `gorm:"foreignkey:address_fk"`
    }
    

    和个人资料地址

    type ProfileAddress struct {
      gorm.Model
      Archive bool `json:"archive"`
    
      Profile Profile
      Address Address
      AddressFK int`gorm:"ForeignKey:id"`
      ProfileFK int`gorm:"ForeignKey:id"`
    }
    

    /profile/add (邮递员)包括以下数据

    {
      "company": "testing-000001",
      "date_added": "3051-11-09T00:00:00+00:00",
      "address_id": 3
    }
    

    现在我可以保存一个新的配置文件和一个新的地址,但不保存这个数据。我刚刚加了 json:"address_id"` Profile struct 但这并没有奏效。

    那我做错什么了?

    欢迎任何帮助。

    1 回复  |  直到 7 年前
        1
  •  0
  •   C0ol_Cod3r    7 年前

    这是我如何得到它的工作,请让我知道,如果这是不正确的,或者如果有更好的方法。

    Profile 结构到包装器/嵌套结构,如下所示:

    type ProfileWrapper struct {
      gorm.Model
      ProfileData Profile
      AddressID int `json:"address_id"`
    }
    

    因此,我将发送到此结构中的json数据更改/更新为:

    {
      "ProfileData": {
          "company": "testing-with-add-0001",
          "date_added": "9067-11-09T00:00:00+00:00"
      },
      "address_id": 3
    }
    

    所以为了保存档案我做了这个,

    db.Create( &p.ProfileData )
    

    pd := structs.ProfileAddress{AddressFK: p.AddressID, ProfileFK: profileID}
    
    db.Create( &pd )
    

    不确定这是否是最好的方法,但它似乎工作。如果这是错误的,请让我知道。

    谢谢。