登录
首页 >  Golang >  Go问答

GORM 中的多个一对多关系

来源:stackoverflow

时间:2024-03-17 08:27:29 232浏览 收藏

在使用 GORM 管理复杂的数据模型时,需要处理多个一对多关系的情况。这篇文章将指导你如何基于一个模型 ID 获取其所有相关模型的信息,例如一个故事及其所有段落和句子。本文还提供了使用 GORM 预加载功能的示例代码,演示如何高效地获取相关数据,避免多次数据库查询。通过使用 GORM 的预加载功能,你可以优化查询性能,获得完整的数据结构,方便后续处理和展示。

问题内容

我在 go 中有一个 struct 定义,如下所示

package models

//StoryStatus indicates the current state of the story
type StoryStatus string

const (
    //Progress indicates a story is currenty being written
    Progress StoryStatus = "progress"
    //Completed indicates a story was completed
    Completed StoryStatus = "completed"
)

//Story holds detials of story
type Story struct {
    ID         int
    Title      string      `gorm:"type:varchar(100);unique_index"`
    Status     StoryStatus `sql:"type ENUM('progress', 'completed');default:'progress'"`
    Paragraphs []Paragraph `gorm:"ForeignKey:StoryID"`
}

//Paragraph is linked to a story
//A story can have around configurable paragraph
type Paragraph struct {
    ID        int
    StoryID   int
    Sentences []Sentence `gorm:"ForeignKey:ParagraphID"`
}

//Sentence are linked to paragraph
//A paragraph can have around configurable paragraphs
type Sentence struct {
    ID          uint
    Value       string
    Status      bool
    ParagraphID uint
}

我在 go 中使用 gorm 作为 orm。 如何基于 story id 获取 story 的所有信息,例如每个 paragraph 的所有 paragraphs 和所有 sentences

gorm 示例仅显示 2 个模型使用 preload


解决方案


这就是您要找的:

db, err := gorm.open("mysql", "user:password@/dbname?charset=utf8&parsetime=true&loc=local")
defer db.close()

story := &story{}
db.preload("paragraphs").preload("paragraphs.sentences").first(story, 1)

它找到 id = 1 的故事并预加载其关系

fmt.printf("%+v\n", story)

这可以很好地为您打印结果

旁注: 您可以打开 gorm 的日志模式,以便您可以查看底层查询、进行调试或任何其他目的:

db.logmode(true)
Looking this [example][1] this One to many.


package main

import (
    "log"

    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/sqlite"
    "github.com/kylelemons/godebug/pretty"
)

// Order
type Order struct {
    gorm.Model
    Status     string
    OrderItems []OrderItem
}

// Order line item
type OrderItem struct {
    gorm.Model
    OrderID  uint
    ItemID   uint
    Item     Item
    Quantity int
}

// Product
type Item struct {
    gorm.Model
    ItemName string
    Amount   float32
}

var (
    items = []Item{
        {ItemName: "Go Mug", Amount: 12.49},
        {ItemName: "Go Keychain", Amount: 6.95},
        {ItemName: "Go Tshirt", Amount: 17.99},
    }
)

func main() {
    db, err := gorm.Open("sqlite3", "/tmp/gorm.db")
    db.LogMode(true)
    if err != nil {
        log.Panic(err)
    }
    defer db.Close()

    // Migrate the schema
    db.AutoMigrate(&OrderItem{}, &Order{}, &Item{})

    // Create Items
    for index := range items {
        db.Create(&items[index])
    }
    order := Order{Status: "pending"}
    db.Create(&order)
    item1 := OrderItem{OrderID: order.ID, ItemID: items[0].ID, Quantity: 1}
    item2 := OrderItem{OrderID: order.ID, ItemID: items[1].ID, Quantity: 4}
    db.Create(&item1)
    db.Create(&item2)

    // Query with joins
    rows, err := db.Table("orders").Where("orders.id = ? and status = ?", order.ID, "pending").
        Joins("Join order_items on order_items.order_id = orders.id").
        Joins("Join items on items.id = order_items.id").
        Select("orders.id, orders.status, order_items.order_id, order_items.item_id, order_items.quantity" +
            ", items.item_name, items.amount").Rows()
    if err != nil {
        log.Panic(err)
    }

    defer rows.Close()
    // Values to load into
    newOrder := &Order{}
    newOrder.OrderItems = make([]OrderItem, 0)

    for rows.Next() {
        orderItem := OrderItem{}
        item := Item{}
        err = rows.Scan(&newOrder.ID, &newOrder.Status, &orderItem.OrderID, &orderItem.ItemID, &orderItem.Quantity, &item.ItemName, &item.Amount)
        if err != nil {
            log.Panic(err)
        }
        orderItem.Item = item
        newOrder.OrderItems = append(newOrder.OrderItems, orderItem)
    }
    log.Print(pretty.Sprint(newOrder))
}

      [1]: https://stackoverflow.com/questions/35821810/golang-gorm-one-to-many-with-has-one

以上就是《GORM 中的多个一对多关系》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>