英文:
Find a model with empty association in Gorm
问题
我有一个具有BelongsTo关联的模型。我的目标是找到所有具有空关联的Foos
,即没有设置Bar
的Foo
。到目前为止,我还没有找到一个方法。
type Foo struct {
gorm.Model
Name string
BarID uint
Bar Bar
}
我需要手动检查字段barid
是否为0吗?这听起来不正确。
foo := Foo{}
result := r.db.Where(Foo{Name: "Test", BarID: 0}).First(&foo)
英文:
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)
答案1
得分: 0
在尝试之后,确实发现空关联的值为0,即检查BarID: 0
是否有效。不确定这个值是由Gorm还是数据库生成的。这可能与数据库有关。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论