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