【问题标题】:Multiple One to Many Relations in GORMGORM中的多个一对多关系
【发布时间】:2020-05-16 23:30:13
【问题描述】:

我在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 的所有信息,例如所有paragraphs 和每个sentences 的所有sentences

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

【问题讨论】:

    标签: mysql go one-to-many go-gorm


    【解决方案1】:

    这就是你要找的:

    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)
    

    【讨论】:

      【解决方案2】:
          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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-03
        相关资源
        最近更新 更多