jobs我有一个查询从表及其作者中获取行(每个作业都有一个author),但我想选择特定字段。
type User struct {
ID uint `gorm:"primarykey" json:"-"`
UUID uuid.UUID `gorm:"type:uuid not null" json:"-"`
Email string `gorm:"type:varchar(255); not null" json:"email"`
Name string `gorm:"type:varchar(255); not null" json:"name"`
AvatarURL string `gorm:"type:varchar(255); not null" json:"avatar_url"`
Provider string `gorm:"type:varchar(255); not null" json:"provider"`
ProviderID string `gorm:"type:varchar(255); not null" json:"-"`
Jobs []Job `json:"-"`
}
type Job struct {
ID uint `gorm:"primarykey" json:"id"`
Title string `gorm:"type:varchar(255); not null" json:"title"`
Content string `gorm:"not null" json:"content"`
UserID uint `json:"-"`
User User `json:"author"`
}
func (jobRepo repository) FindAll() ([]entity.Job, error) {
var jobs []entity.Job
if dbc := jobRepo.db.Preload("User", func(db *gorm.DB) *gorm.DB {
return db.Select("Name", "Email")
}).Find(&jobs); dbc.Error != nil {
return nil, dbc.Error
}
return jobs, nil
}
Run Code Online (Sandbox Code Playgroud)
自定义预载未按预期运行。如果我不指定具体字段,查询将起作用并返回所有内容。否则,如果我指定某些字段,它不会返回任何内容。
这是因为你没有选择主键。将“ID”添加到 select 子句中:
func(db *gorm.DB) *gorm.DB {
return db.Select("ID", "Name", "Email")
}
Run Code Online (Sandbox Code Playgroud)
否则 GORM 不知道如何将用户加入到工作中。