0

我是新手Golang,请假设我有 2 种型号,如下所示

type Jobs struct {
    JobID                  uint   `json: "jobId" gorm:"primary_key;auto_increment"`
    SourcePath             string `json: "sourcePath"`
    Priority               int64  `json: "priority"`
    InternalPriority       string `json: "internalPriority"`
    ExecutionEnvironmentID string `json: "executionEnvironmentID"`
}

type ExecutionEnvironment struct {
    ExecutionEnvironmentId string    `json: "executionEnvironmentID" gorm:"primary_key;auto_increment"`
    CloudProviderType      string    `json: "cloudProviderType"`
    InfrastructureType     string    `json: "infrastructureType"`
    CloudRegion            string    `json: "cloudRegion"`
    CreatedAt              time.Time `json: "createdAt"`
}

这是我的Database connection& get jobsAPI 代码

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "strconv"
    "time"

    "github.com/gorilla/mux"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
)

type Jobs struct {
    JobID                  uint   `json: "jobId" gorm:"primary_key;auto_increment"`
    SourcePath             string `json: "sourcePath"`
    Priority               int64  `json: "priority"`
    InternalPriority       string `json: "internalPriority"`
    ExecutionEnvironmentID string `json: "executionEnvironmentID"`
}

type ExecutionEnvironment struct {
    ExecutionEnvironmentId string    `json: "executionEnvironmentID" gorm:"primary_key;auto_increment"`
    CloudProviderType      string    `json: "cloudProviderType"`
    InfrastructureType     string    `json: "infrastructureType"`
    CloudRegion            string    `json: "cloudRegion"`
    CreatedAt              time.Time `json: "createdAt"`
}

var db *gorm.DB

func initDB() {
    var err error
    dataSourceName := "root:@tcp(localhost:3306)/?parseTime=True"
    db, err = gorm.Open("mysql", dataSourceName)

    if err != nil {
        fmt.Println(err)
        panic("failed to connect database")
    }
    //db.Exec("CREATE DATABASE test")
    db.LogMode(true)
    db.Exec("USE test")
    db.AutoMigrate(&Jobs{}, &ExecutionEnvironment{})
}

func GetAllJobs(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    fmt.Println("Executing Get All Jobs function")
    // var jobs []Jobs
    // db.Preload("jobs").Find(&jobs)
    // json.NewEncoder(w).Encode(jobs)
    var jobs []Jobs
    if err := db.Table("jobs").Select("*").Joins("JOIN execution_environments on execution_environments.execution_environment_id = jobs.execution_environment_id").Find(&jobs).Error; err != nil {
        fmt.Println(err)
    }
    json.NewEncoder(w).Encode(jobs)
}


func main() {
    // router
    router := mux.NewRouter()
    // Access URL
    router.HandleFunc("/GetAllJobs", GetAllJobs).Methods("GET")
    
    // Initialize db connection
    initDB()

    // config port
    fmt.Printf("Starting server at 8000 \n")
    http.ListenAndServe(":8000", router)
}

GetAllJobs我尝试获取jobs表数据和execution_environments表数据。但我的代码不是fetch execution_environments表格数据。请检查以下示例json

[
    {
        "JobID": 4,
        "SourcePath": "test1",
        "Priority": 2,
        "InternalPriority": "test",
        "ExecutionEnvironmentID": "103"
    }
]

jobs table 在此处输入图像描述

execution_environments table 在此处输入图像描述

请帮我获取我的execution_environments表格数据json

4

2 回答 2

1

Jobs如果和之间的关系ExecutionEnvironment是一对一的,那么您的Jobs结构可能如下所示:

type Jobs struct {
    JobID                  uint   `json: "jobId" gorm:"primary_key;auto_increment"`
    SourcePath             string `json: "sourcePath"`
    Priority               int64  `json: "priority"`
    InternalPriority       string `json: "internalPriority"`
    ExecutionEnvironmentID string `json: "executionEnvironmentID"`
    ExecutionEnvironment   ExecutionEnvironment `gorm:"foreignKey:ExecutionEnvironmentID"`
}

接下来,要加载模型ExecutionEnvironment内的字段Jobs,您需要使用Preload函数。

如果您已经在两个表之间定义了关系(外键),您可以像这样获取数据:

var jobs []Jobs
if err := db.Preload("ExecutionEnvironment").Find(&jobs).Error; err != nil {
        fmt.Println(err)
}

如果没有,请尝试包含以下Joins功能:

var jobs []Jobs
if err := db.Preload("ExecutionEnvironment").Joins("JOIN execution_environments ee on ee.execution_environment_id = jobs.execution_environment_id").Find(&jobs).Error; err != nil {
        fmt.Println(err)
}
于 2021-09-22T18:19:19.477 回答
0

Job 和 ExecutionEnvironment 之间的关系是 belongs_to 吗?

https://gorm.io/docs/belongs_to.html

如果是,只需将 ExecutionEnvironment 添加到您的作业结构中

type Jobs struct {
    JobID                  uint   `json: "jobId" gorm:"primary_key;auto_increment"`
    SourcePath             string `json: "sourcePath"`
    Priority               int64  `json: "priority"`
    InternalPriority       string `json: "internalPriority"`
    ExecutionEnvironmentID string `json: "executionEnvironmentID"`
    ExecutionEnvironment   ExecutionEnvironment `gorm:"foreignKey:ExecutionEnvironmentID"`
}

你应该能够得到 ExecutionEnvironment 数据

于 2021-09-22T15:08:05.817 回答