在Gorm中查找一个没有关联的模型。

huangapple go评论74阅读模式
英文:

Find a model with empty association in Gorm

问题

我有一个具有BelongsTo关联的模型。我的目标是找到所有具有空关联的Foos,即没有设置BarFoo。到目前为止,我还没有找到一个方法

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.

huangapple
  • 本文由 发表于 2023年4月19日 06:23:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76049449.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定