使用GoLang保存额外的数据

So I am using Go Lang 1.10.3 with the Echo framework with Gorm and Postgres as my database.

I have the three tables / structs , Profile, Addresses and Profile_addresses

The structs are as follows,

Profile

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

Address

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

And Profile Address

type ProfileAddress struct {
  gorm.Model
  Archive bool `json:"archive"`

  Profile Profile
  Address Address
  AddressFK int`gorm:"ForeignKey:id"`
  ProfileFK int`gorm:"ForeignKey:id"`
}

These tables all get made fine but I am now trying to save an address ID to the Profile Address table when making a new Profile. Posting data to /profile/add (with Postman) including the following data

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

Now I can save a new profile and a new address but not save this data. I have only just added the json:"address_id"` option to the end of the Profile struct but that did not work.

I have set this up like so, as one profile might have many address so there needs to be a linked table with all the address ids. I sure that I could do this in a two stage step, e.g. save the profile, then save the addresses I want to add to that profile but I would like to get this to work. I also dont need to create a new address, these would have already been added into the system.

So what am I doing wrong?

Any help most welcome.

Thanks,

This is how I got it to work, please let me know if this is not correct or if there is a better way.

So I added the Profile struct to a wrapper/nested struct, like so:

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

So I then changed/updated the json data I was sending into this struct to this:

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

So to saved the profile I did this,

db.Create( &p.ProfileData )

I then built a new struct for the Profile Address information to be created/added, like so:

pd := structs.ProfileAddress{AddressFK: p.AddressID, ProfileFK: profileID}

db.Create( &pd )

Not sure if this is the best way of doing this, but it seems to work. If this is wrong please let me know.

Thanks.