Issue with Gorm struct

I am working on a simple bird breeding application, because how else do we learn :slight_smile:

So far its working like a charm. i can add/edit/delete birds, the problem arrises when i try to add fields to connect a bird to its parent. The problem is that we dont always have birds of which we have the parents too. But the best i can come up with is this struct:

type Bird struct {
	gorm.Model
	RingNo   string `gorm:"not null"`
	Species  string `gorm:"not null"`
	Color    string `gorm:"not null"`
	■■■      string `gorm:"not null"`
	UserID   uint   `gorm:"not null"`
	User     User
	FatherID *uint
	Father   *Bird `gorm:"foreignKey:FatherID;default:SET NULL"`
	MotherID *uint
	Mother   *Bird `gorm:"foreignKey:MotherID;default:SET NULL"`
	Notes    []BirdNote `gorm:"foreignKey:BirdID"`
}

Basicly, what i’m trying to achieve is that FatherID and MotherID can be empty, but whatever i try, i always end up with a “violates key contraint” error :frowning:

When i make everything a string it works. But then i have to manually fill in the FatherID and the MotherID. in the ideal situation i could link the bird to the RingNo of its father and mother, using a drop down menu. (or leave it empty if i dont know the father and mother)

I haven’t used gorm but searching for “gorm foreign key nullable” I found these two links that seem promising:

  1. postgresql - How to insert a null foreign key in gorm? - Stack Overflow
  2. How to create nullable foreign key in gorm/v2 · Issue #3188 · go-gorm/gorm · GitHub

I can’t say which solution will work best, or even if you need to tweak them further, but I hope they will be of some use to you. Many hatchings to you. :slight_smile:

1 Like