GORM中的多个一对多关系

我有这样的struct定义GO


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

}

我GORM在 GO 中使用 for orm。如何story基于story idlike allparagraphs和 all the sentencesfor each获取 a 的所有信息paragraph。


该GORM示例仅显示使用 2 个模型preload


翻阅古今
浏览 213回答 2
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)

忽然笑

    Looking this [example][1] this One to many.package mainimport (    "log"    "github.com/jinzhu/gorm"    _ "github.com/jinzhu/gorm/dialects/sqlite"    "github.com/kylelemons/godebug/pretty")// Ordertype Order struct {    gorm.Model    Status     string    OrderItems []OrderItem}// Order line itemtype OrderItem struct {    gorm.Model    OrderID  uint    ItemID   uint    Item     Item    Quantity int}// Producttype 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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go