dongyou6768 2019-04-08 12:45
浏览 210
已采纳

Gorm仅返回一个而不是多个结果

I wrote blow codes and it returns just 1 row instead of 4:

package main

import (
    "fmt"

    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/sqlite"
)

type Post struct {
    gorm.Model
    Title    string
    Text     string
    Comments []Comment
}

type Comment struct {
    gorm.Model
    Text   string
    PostID uint `gorm:"foreignkey:ID;association_foreignkey:PostID"`
}

func main() {
    db, err := gorm.Open("sqlite3", "test.db")
    if err != nil {
        panic("failed to connect to database")
    }
    defer db.Close()

    db.DropTableIfExists(&Post{}, &Comment{})
    db.AutoMigrate(&Post{}, &Comment{})

    // fill db
    db.Create(&Post{Title: "test1 title", Text: "text1"})
    db.Create(&Post{Title: "test2 title", Text: "text2"})
    db.Create(&Post{Title: "test3 title", Text: "text3"})
    db.Create(&Comment{Text: "test1 comment1", PostID: 3})
    db.Create(&Comment{Text: "test2 comment1", PostID: 2})
    db.Create(&Comment{Text: "test3 comment2", PostID: 2})
    db.Create(&Comment{Text: "test4 comment3", PostID: 2})
    db.Create(&Comment{Text: "test5 comment4", PostID: 2})
    db.Create(&Comment{Text: "test6 comment1", PostID: 1})
    //end fill db

    var myPost Post
    var comments Comment
    db.First(&myPost, 2)
    db.Model(&myPost).Related(&comments)

    fmt.Println(myPost)
    fmt.Println(comments)
}

and this is my output:

{{2 2019-04-08 17:04:20.3781288 +0430 +0430 2019-04-08 17:04:20.3781288 +0430 +0430 <nil>} test2 title text2 []}
{{5 2019-04-08 17:04:20.4091133 +0430 +0430 2019-04-08 17:04:20.4091133 +0430 +0430 <nil>} test5 comment4 2}

you can see just one row:

test5 comment4 

and I expect this result:

test2 comment1
test3 comment2
test4 comment3
test5 comment4

What should I do to get 4 rows result?

I already read all the documentation of gorm. and this example of doc is not working for me as I expect http://doc.gorm.io/associations.html#has-many

Has Many
// User has many emails, UserID is the foreign key
type User struct {
    gorm.Model
    Emails   []Email
}

type Email struct {
    gorm.Model
    Email   string
    UserID  uint
}

db.Model(&user).Related(&emails)
//// SELECT * FROM emails WHERE user_id = 111; // 111 is user's primary key
  • 写回答

2条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥30 Dijkstra‘s 最短路径
      • ¥15 在线教育培训平台,主要以点播视频和在线练习测试为主,除将视频做切片外,有其他哪种方式降低流量?(关键词-带宽速率)
      • ¥20 用c语音或c++实现银行叫号系统
      • ¥15 人工智能 规则正向演绎和推理
      • ¥20 基于STM32F401的电子密码锁设计
      • ¥15 famamacbeth回归中遇到only size-1 arrays can be converted to Python scalars,求解答
      • ¥15 单片机多个自锁按键的编程实践
      • ¥15 用python操作redis存储中文后,再取出的数据变成了乱码怎么办?
      • ¥15 C语言简单排序问题有偿求解
      • ¥20 请问图片的代码什么意思