gorm Create function but only able to create associations, not to update the associated field

Viewed 33

I have the following two structs:

type User struct {
    ID          uuid.UUID      `gorm:"type:uuid"`
    Name        string         `gorm:"not null"`
    CreditCards []*CreditCard  `gorm:"many2many:user_creditcards;"`
}

type CreditCard struct {
    ID         uuid.UUID  `gorm:"type:uuid"`
    Number     string     `gorm:"not null"`
}

And I want to create "separately" the users and the credit cards. So, if I want to create a new user with different credit cards, the credit cards need to previously being created.

So then, imagine that I create the following user:

user := User{
    Name: "My username"
    CreditCard: []*CreditCard{CreditCard{ID:xxxxxx}}
}

As you can see, I don't populate all the fields of the credit card, because it's already existing, so I just want to add the link between the user I want to create, and the already existing credit card.

For that I am trying the following:

db.Model(&User{}).Create(&user) but it's complaining that the creditCard.Number it's null. I also tried:

db.Model(&User{}).Omit(clause.Associations()).Create(&user)

but I am still getting the same error.

Am I missing something?

1 Answers

Use This

package main

import (
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
)

type Database struct {
    Gorm *gorm.DB
}

func NewDatabase(url string) (*Database, error) {
    cfg := &gorm.Config{}

    db, err := gorm.Open(mysql.Open(url), cfg)
    if err != nil {
        return nil, err
    }

    instance := &Database{
        Gorm: db,
    }

    err = instance.setup()
    if err != nil {
        return nil, err
    }

    return instance, nil
}
func (rDb *Database) setup() error {
    return rDb.Gorm.AutoMigrate(
        &User{},
        &CreditCard{},
    )
}

type User struct {
    gorm.Model
    Name        string        `gorm:"not null"`
    CreditCards []*CreditCard `gorm:"many2many:user_credit_cards;"`
}

type CreditCard struct {
    gorm.Model
    Number string `gorm:"not null"`
}

func main() {
    database, _ := NewDatabase("root:root@tcp(127.0.0.1:3306)/OrderManager?parseTime=true")
    var user = User{
        Name: "My username",
        CreditCards: []*CreditCard{
            {
                Model: gorm.Model{
                    ID: 1,
                },
            },
        },
    }
    database.Gorm.Create(&user)
}

Related