在 Gorm 中結合 2 個或更多模型生成結構結果的最佳方法是什么?
給定這些示例模型:
type Book struct {
gorm.Model
Title string
Description string
AuthorID uint
}
type Author struct {
gorm.Model
FirstName string
LastName string
Books []Book
}
我想創建一個查詢以按標題查找書籍
db.Where("title=?", "foo").Find(&books)
到目前為止沒問題,但我還想在結果中包含 Author.FirstName 和 Author.LastName。這不適用于我嘗試過的任何方法,因為 Book 結構不包含這些欄位。所需的結果應包括匹配書籍的所有欄位以及與該書籍相關的作者的所有欄位。
嘗試使用 Select() 和 Join() 函式來指定所有需要的欄位,這產生了正確的 SQL 陳述句,但生成的 Book 結構仍然不包含任何 Author 欄位。
uj5u.com熱心網友回復:
我能夠以這種方式完成您的要求。
首先,我在結構中添加了Author Author欄位。Book這樣,您可以將作者的資訊與他的書籍一起保存。
在查詢中,您必須使用Preload("Auhtor")GORM 來加載authors表中的資訊。這種做法稱為急切加載。在下面,您可以找到我的作業解決方案:
package main
import (
"fmt"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
type Book struct {
gorm.Model
Title string
Description string
AuthorID uint
Author Author
}
type Author struct {
gorm.Model
FirstName string
LastName string
Books []Book
}
func main() {
dsn := "host=localhost user=postgres password=postgres dbname=postgres port=5432 sslmode=disable"
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
panic(err)
}
db.AutoMigrate(&Book{})
db.AutoMigrate(&Author{})
book1 := &Book{Title: "Go", Description: "Intro to Golang", AuthorID: 1}
book2 := &Book{Title: "GORM", Description: "Intro to GORM", AuthorID: 1}
author := &Author{FirstName: "John", LastName: "Doe", Books: []Book{*book1, *book2}}
db.Create(author)
var books []Book
db.Preload("Author").Where("title=?", "Go").Find(&books)
for _, v := range books {
fmt.Println("book 1:")
fmt.Printf("title: %q\n\n", v.Title)
fmt.Printf("author details:\n")
fmt.Printf("first name: %q\n", v.Author.FirstName)
fmt.Printf("last name: %q\n", v.Author.LastName)
}
}
希望這可以幫助您理解。
uj5u.com熱心網友回復:
請看下面的例子,看看我們如何在 Gorm 中生成一個包含兩個或多個模型的結構。
type Driver struct {
gorm.Model
Name string
License string
Cars []Car
}
type Car struct {
gorm.Model
Year int
Make string
ModelName string
DriverID int
}
var (
drivers = []Driver{
{Name: "Shashank", License: "India123"},
{Name: "Tom", License: "India321"},
}
cars = []Car{
{Year: 2000, Make: "Toyota", ModelName: "Tundra", DriverID: 1},
{Year: 2001, Make: "Honda", ModelName: "Accord", DriverID: 1},
}
)
func GetCars(w http.ResponseWriter, r *http.Request) {
var cars []Car
db.Find(&cars)
json.NewEncoder(w).Encode(&cars)
}
// Getting cars with the id, where it will include name of driver & license
func GetCar(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
var car Car
db.First(&car, params["id"])
json.NewEncoder(w).Encode(&car)
}
請注意,這不是完整的代碼,它基本上是您的解決方案的參考,您可以查看我的存盤庫的完整代碼。 https://github.com/amshashankk/GO_Postgres_Testing/blob/main/main.go
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/530853.html
標籤:去戈戈姆
