Custom Gorm preloading does not fetch data

我是研究僧i 提交于 2021-01-18 06:28:11

问题


I have a query that fetches rows from jobs table and its author (each job has an author), but I want to select specific fields.

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
}

The custom preload does not behave as desired. If I do not specify concrete fields, the query works and returns everything. Otherwise, If I specify some fields, it returns nothing.


回答1:


This is because you didn't select primary key. Add "ID" into select clause:

func(db *gorm.DB) *gorm.DB {
    return db.Select("ID", "Name", "Email")
}

Otherwise GORM doesn't know how to join users to jobs.



来源:https://stackoverflow.com/questions/65288705/custom-gorm-preloading-does-not-fetch-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!