ninesalt
ninesalt

Reputation: 4354

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?

Upvotes: 14

Views: 8478

Answers (2)

Sergei888 Kuz
Sergei888 Kuz

Reputation: 61

Use gorm struct annotation: gorm:"default:null" instead of pointer.
Example where AccountChangeCategoryID could be null:

type AccountChange struct {
    general.Model
    /*
        If positive - income
        If negative - expense
    */
    Value                   float64 `json:"value"`
    Name                    string  `json:"name"`
    AccountID               uint    `json:"account_id"`
    AccountChangeCategoryID uint    `json:"category_id" gorm:"default:null"`
}

Upvotes: 6

fonini
fonini

Reputation: 3341

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

TradeID     *int 

Upvotes: 18

Related Questions