我有以下模型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}但我想把它变成一个查询。关于如何实现这一目标的任何想法?
1 回答
梦里花落0921
TA贡献1772条经验 获得超6个赞
您始终可以使用联接函数来执行 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
}
- 1 回答
- 0 关注
- 74 浏览
添加回答
举报
0/150
提交
取消