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?

2 Answers 2

19

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

TradeID *int 
Sign up to request clarification or add additional context in comments.

1 Comment

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?
6

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"` } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.