【踩坑】Gorm查询关联表时SQL语句有误

前言

Gorm查询关联表时SQL语句有误

原因

  • 某表结构体(User)与其关联表结构体(Name)都有一个名为ID的字段和一个名为NameID的字段,并且同时定义了foreignKey标签和references标签

在User结构体中的NameID字段是外键
在Name结构体中的NameID字段是为了表示其上级Name,也起名叫做了NameID

1
2
3
4
5
6
7
8
9
10
11
type User struct {
ID uint
NameID uint
Name Name `gorm:"foreignKey:NameID;references:ID"`
}

type Name struct {
ID uint
NameID uint
Name *Name
}
  • 导致Gorm理解程序意图时出错,无法判断是Belongs To模式关联还是Has One模式关联

该情况既可以理解成foreignKey标注了User.IDreferences标注了Name.ID,也可以理解成foreignKey标注了Name.IDreferences标注了User.NameID
我的意图是Has One,但是Gorm理解的是Belongs To,因为两种情况同时满足时,Gorm的缺省值是Belongs To

解决问题

  • 不要使用foreignKey标签,而是仅使用references标签标注关联表的主键
1
2
3
4
5
6
7
8
9
10
11
type User struct {
ID uint
NameID uint
Name Name `gorm:"references:ID"`
}

type Name struct {
ID uint
NameID uint
Name *Name
}
  • 或者既不使用foreignKey标签,也不使用references标签,而是尝试让Gorm自动判断关联关系
1
2
3
4
5
6
7
8
9
10
11
type User struct {
ID uint
NameID uint
Name Name
}

type Name struct {
ID uint
NameID uint
Name *Name
}

完成