Search code examples
gogo-gorm

Find a model with empty association in Gorm


I have an model with a BelongsTo association. My goal is to find all Foos with an empty association, i.e. no Bar is set. So far I have not found a method.

type Foo struct {
    gorm.Model
    Name    string
    BarID   uint
    Bar     Bar
}

Do I have to manually check if the field barid is 0? This sounds incorrect.

foo := Foo{}
result := r.db.Where(Foo{Name: "Test", BarID: 0}).First(&foo)

Solution

  • After playing around it indeed seems that the value for an empty association is 0, i.e. checking for BarID: 0 works. Not sure if this value is generated by Gorm or the database. Then it would be database dependent.