Golang gorm join 2nd table data's now come

拉梅什

是新来的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

艾敏·拉莱托维奇

如果之间的关系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)
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章