我有以下模型
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
}