将两个 gorm 查询变成一个
Turn two gorm queries into one
我有以下型号
type Instance struct {
gorm.Model
Name string `gorm:"index:idx_name_and_group,unique"`
UserID uint
GroupID uint `gorm:"index:idx_name_and_group,unique"`
...
}
type Group struct {
gorm.Model
Name string `gorm:"unique;"`
Instances []Instance
...
}
我正在尝试按名称和组名获取实例。
我可以使用下面的代码来完成
func (r instanceRepository) FindByName(groupName string, instanceName string) (*model.Instance, error) {
var instance *model.Instance
var group *model.Group
err := r.db.
First(&group, "name = ?", groupName).Error
if err != nil {
return nil, err
}
err = r.db.
Where("name = ? and group_id = ?", instanceName, group.ID).
First(&instance).Error
return instance, err
}
但我想把它变成一个查询。关于如何实现这一点有什么想法吗?
您始终可以使用 Joins 函数进行 SQL 连接。像这样:
func (r instanceRepository) FindByName(groupName string, instanceName string) (*model.Instance, error) {
var instance *model.Instance
err := r.db.
Joins("INNER JOIN groups g ON g.id = instances.group_id").
Where("g.name = ? AND instances.name = ?", groupName, instanceName).
First(&instance).Error
if err != nil {
return nil, err
}
return instance, err
}
我有以下型号
type Instance struct {
gorm.Model
Name string `gorm:"index:idx_name_and_group,unique"`
UserID uint
GroupID uint `gorm:"index:idx_name_and_group,unique"`
...
}
type Group struct {
gorm.Model
Name string `gorm:"unique;"`
Instances []Instance
...
}
我正在尝试按名称和组名获取实例。
我可以使用下面的代码来完成
func (r instanceRepository) FindByName(groupName string, instanceName string) (*model.Instance, error) {
var instance *model.Instance
var group *model.Group
err := r.db.
First(&group, "name = ?", groupName).Error
if err != nil {
return nil, err
}
err = r.db.
Where("name = ? and group_id = ?", instanceName, group.ID).
First(&instance).Error
return instance, err
}
但我想把它变成一个查询。关于如何实现这一点有什么想法吗?
您始终可以使用 Joins 函数进行 SQL 连接。像这样:
func (r instanceRepository) FindByName(groupName string, instanceName string) (*model.Instance, error) {
var instance *model.Instance
err := r.db.
Joins("INNER JOIN groups g ON g.id = instances.group_id").
Where("g.name = ? AND instances.name = ?", groupName, instanceName).
First(&instance).Error
if err != nil {
return nil, err
}
return instance, err
}