Golang gorm 加入第二个表的数据现在已经到来。

huangapple go评论71阅读模式
英文:

Golang gorm join 2nd table data's now coming

问题

我是你的中文翻译助手,以下是翻译好的内容:

我是Golang的新手,请假设我有以下两个模型:

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"`
}

这是我的数据库连接获取作业的API代码:

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表的数据。但是我的代码没有获取到execution_environments表的数据。请检查下面的示例json

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

jobs表:
Golang gorm 加入第二个表的数据现在已经到来。

execution_environments表:
Golang gorm 加入第二个表的数据现在已经到来。

请帮助我在我的json中获取execution_environments表的数据。

英文:

Am new in Golang, Please assume I have 2 models like below

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"`
}

This is my Database connection & get jobs API code

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)
}

In GetAllJobs I try to get jobs table data and execution_environments table data's. But my code not fetch execution_environments table data. Please check sample json below:

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

jobs table
Golang gorm 加入第二个表的数据现在已经到来。

execution_environments table
Golang gorm 加入第二个表的数据现在已经到来。

Please help me to fetch the execution_environments table data's in my json

答案1

得分: 3

如果JobsExecutionEnvironment之间的关系是一对一的,你的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"`
}

接下来,要在Jobs模型中加载ExecutionEnvironment字段,你需要使用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)
}
英文:

If the relationship between Jobs and ExecutionEnvironment is one-on-one, your Jobs struct might look like this:

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"`
}

Next, to load the ExecutionEnvironment field inside the Jobs model, you need to use the Preload function.

If you already have a defined relationship (foreign key) between the two tables, you can fetch the data like this:

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

If not, try including the Joins function:

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)
}

答案2

得分: 0

工作(Job)和执行环境(ExecutionEnvironment)之间的关系是属于(belongs_to)关系吗?

如果是的话,只需将ExecutionEnvironment添加到您的job结构中:

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的数据。

英文:

Is the relation between the Job and ExecutionEnvironment a belongs_to ?

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

if yes, simply add the ExecutionEnvironment to your job struct

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"`
}

and you should be able to get the ExecutionEnvironment data

huangapple
  • 本文由 发表于 2021年9月22日 21:23:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/69285123.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定