Search code examples
postgresqlgogo-gorm

How to insert a null foreign key in gorm?


I have a transaction table in gorm that looks like this:

type Transaction struct {
    gorm.Model
    UserID      string `gorm:"index"`
    TradeID     int 
    Trade       Trade
    ExternalID  string
    Amount      float32
    Type        string
    Description string
}

And I'm trying to insert a transaction without a trade:

DB.Create(&Transaction{UserID: "user-1", Type: "unblock", Amount:  50})

This fails because the Transaction structs defaults the int value of the key to 0 so the insert fails at the db level because I don't have a trade with id = 0.

How can I do this?


Solution

  • You can change the TradeID to a pointer, so the default value will be nil.

    TradeID     *int