How to insert a null foreign key in gorm?
Asked Answered
J

2

14

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?

Jaqitsch answered 10/3, 2021 at 11:26 Comment(0)
M
18

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

TradeID     *int 
Mathewmathews answered 10/3, 2021 at 11:48 Comment(1)
How would I search for a TradeID with value of e.g. 3 then? Passing a pointer to 3 would not work I guess since the pointer address is always different, right?Vivianne
E
5

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"`
}
Exclaim answered 20/6, 2023 at 21:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.