gorm:can't preload field Repository for main.Application

siotufzp  于 11个月前  发布在  Go
关注(0)|答案(1)|浏览(125)

当访问这个端点时,我得到以下错误,然后是进程退出:

2023/11/16 20:13:38 can't preload field Repository for main.Application
exit status 1

字符串
我正在尝试预加载存储库,这样我就可以在前端访问存储库的URL
路由处理程序:

func ApplicationsHandler(w http.ResponseWriter, r *http.Request) {
    var applications []Application
    var queryError = database.Model(Application{}).
        Preload("Repository").
        Find(&applications).
        Error

    if queryError != nil {
        log.Fatalln(queryError)
    }

    json.NewEncoder(w).Encode(applications)
}


结构:

type Application struct {
    ID         int64                 `json:"id" gorm:"primary_key"`
    Name       string                `json:"name"`
    Repository ApplicationRepository `json:"repository_id" gorm:"ForeignKey:repository_id"`
    Username   string                `json:"username"`
    IpAddress  string                `json:"ip_addreess"`
}

type ApplicationRepository struct {
    ID  int64  `json:"id" gorm:"primary_key"`
    Url string `json:"url"`
}

bq3bfh9z

bq3bfh9z1#

您需要在ApplicationRepository中添加ApplicationID以获得关系。

type Application struct {
    ID         int64                 `json:"id" gorm:"primary_key"`
    Name       string                `json:"name"`
    Repository ApplicationRepository `json:"repository"`
    Username   string                `json:"username"`
    IpAddress  string                `json:"ip_addreess"`
}

type ApplicationRepository struct {
    ID  int64  `json:"id" gorm:"primary_key"`
    Url string `json:"url"`
    ApplicationID `json:"application_id"`
}

字符串

相关问题