Reputation: 21
This is my code I'm not sure what went wrong the value which is in the user is getting updated in the user table properly but the address struct value is not storing the data in the address table
I want to save two users and address table with one struct association please kindly help me out. Please Help me out
db.Table(models.TABLE_USER).AutoMigrate(&models.User{})
db.Table(models.TABLE_USER_ADDRESS).AutoMigrate(&models.UserAddress{})
type User struct {
UserId string `json:"user_id" gorm:"column:user_id;not null; primarykey"`
ClientID string `json:"cliend_id" gorm:"unique;type:varchar(100);not null"`
SecertKey string `json:"secert_key" gorm:"unique;type:varchar(100);not null"`
ClientSecretKey string `json:"client_secert_key" gorm:"unique;type:varchar(100);not null"`
FirstName string `json:"first_name" gorm:"varchar(100);not null"`
LastName string `json:"last_name" gorm:"varchar(100);not null"`
Address []UserAddress `json:"address" gorm:"foreignKey:Id;references:UserId"`
Email string `json:"email" gorm:"column:email;not null"`
Phone string `json:"phone_no" gorm:"column:phone_no;not null"`
CreatedDate time.Time `json:"created_date" gorm:"column:created_date"`
UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at"`
}
type UserAddress struct {
Id string `json:"id" gorm:"column:id;not null;primaryKey"`
Street1 string `json:"street1" gorm:"column:street1"`
Street2 string `json:"street2" gorm:"column:street2"`
City string `json:"city" gorm:"column:city"`
State string `json:"state" gorm:"column:state"`
Country string `json:"country" gorm:"column:country"`
}
func TestUserCreation(t *testing.T) {
appconf := GetAppConfig()
var user models.User
user.UserId = "123456trds"
user.ClientID = "1234321qws"
user.Email = "[email protected]"
user.FirstName = "xyz"
user.LastName = "acr"
user.Phone = "9213430981"
user.SecertKey = "09jfinbdskj"
user.ClientSecretKey = "qwdcesdf"
a := []models.UserAddress{}
aj := append(a, models.UserAddress{
Id: "123456trds",
City: "Bengaluru",
Street1: "Street1",
Street2: "Street2",
Country: "India",
})
user.Address = aj
user.CreatedDate = time.Now()
user.UpdatedAt = time.Now()
fmt.Println(user)
rs := repo.NewUserRepo(appconf)
err := rs.Create(&user)
if helpers.HasError(&err) {
fmt.Println(err)
}
}
func (r *UserRepo) Create(user *models.User) errors.RestAPIError {
db := r.DB
fmt.Println("BD", user)
if err := db.Table(models.TABLE_USER).Save(&user).Error; err != nil {
fmt.Println(err)
return errors.NewInternalServerError("Cannot save user in db")
}
return errors.NO_ERROR()
}
Upvotes: 1
Views: 372
Reputation: 59
Use Create
instead of Save
.
And check out this article.
https://gorm.io/docs/associations.html#Auto-Create-x2F-Update
Upvotes: 0