英文:
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"
}
]
请帮助我在我的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"
}
]
Please help me to fetch the execution_environments
table data's in my json
答案1
得分: 3
如果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"`
}
接下来,要在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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论