为了账号安全,请及时绑定邮箱和手机立即绑定

GORM中的多个一对多关系

GORM中的多个一对多关系

Go
翻阅古今 2022-05-10 16:23:25
我有这样的struct定义GOpackage models//StoryStatus indicates the current state of the storytype StoryStatus stringconst (    //Progress indicates a story is currenty being written    Progress StoryStatus = "progress"    //Completed indicates a story was completed    Completed StoryStatus = "completed")//Story holds detials of storytype 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 paragraphtype Paragraph struct {    ID        int    StoryID   int    Sentences []Sentence `gorm:"ForeignKey:ParagraphID"`}//Sentence are linked to paragraph//A paragraph can have around configurable paragraphstype Sentence struct {    ID          uint    Value       string    Status      bool    ParagraphID uint}我GORM在 GO 中使用 for orm。如何story基于story idlike allparagraphs和 all the sentencesfor each获取 a 的所有信息paragraph。该GORM示例仅显示使用 2 个模型preload
查看完整描述

2 回答

?
小唯快跑啊

TA贡献1863条经验 获得超2个赞

这就是你要找的:


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)


查看完整回答
反对 回复 2022-05-10
?
忽然笑

TA贡献1806条经验 获得超5个赞

    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


查看完整回答
反对 回复 2022-05-10
  • 2 回答
  • 0 关注
  • 212 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号