我写了打击代码,它只返回1行而不是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)
}
这是我的输出:
{{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}
您只能看到一行:
test5 comment4
我希望得到这个结果:
test2 comment1
test3 comment2
test4 comment3
test5 comment4
我应该怎么做才能得到4行结果?
我已经阅读了gorm的所有文档。而且这个doc范例对我不起作用 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
答案 0 :(得分:1)
附件中有很多问题,将一一解决:
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"`
}
在这里,外键foreignkey:ID
的分配以及关联外键都是不必要的且放错了位置。
对于Foreign Key:默认情况下,gorm使用所有者的类型名称加上其主键字段的名称。对于您的情况:PostID
。
Post
是所有者的类型名称 ID
是其主键。如果要更改forignkey
结构中的领域名称,则仅需要使用Comment
标记。例如,用PostNumber
代替PostID
。因此,您需要添加带有foreignkey:PostNumber
的标签,并将Comment
中的PostID更改为PostNumber
。
对于Association ForeignKey,如果要告诉gorm使用所有者的主键以外的其他成员,则使用它。例如,在下面的示例中,AnotherID
。
另一个问题是您应该在has many
字段上指定这些标签,而不是外键本身。一个完整的示例如下所示:
type Post struct {
gorm.Model
AnotherID uint <-------------------------------------------------------
Title string |
Text string |
Comments []Comment `gorm:"foreignkey:PostNumber;association_foreignkey:AnotherID"`
} |
|
type Comment struct { |
gorm.Model |
Text string |
PostNumber uint <----------------------
}
请注意,这两个必须具有相同的类型。
有人可以争论defer db.Close()
的用法。在docs中,
关闭数据库很罕见,因为该数据库句柄是长期存在的并且在许多goroutine之间共享。
在此示例中,可以defer
关闭数据库。不过,如果您不调用它,它将自动发生。我对此进行评论的主要原因是告诉您,在大型应用程序中,您不需要为每个连接都这样做。只需在全局变量上调用sql.Open()
即可使用,而无需db.Close()
。
在这种情况下,您也不希望它打开任意数量的连接,因此您可能需要微调以下参数:
db.DB().SetConnMaxLifetime(X) // sets the maximum amount of time a connection may be reused.
db.DB().SetMaxIdleConns(X) // sets the maximum number of connections in the idle connection pool.
db.DB().SetMaxOpenConns(X) // sets the maximum number of open connections to the database.
有关更多信息,请参见this讨论。
以下呼叫可能失败:
db.DropTableIfExists(&Post{}, &Comment{})
db.AutoMigrate(&Post{}, &Comment{})
db.Create(&Post{Title: "test1 title", Text: "text1"})
因此,总是检查错误,您可以通过检查Error
结构的gorm.DB
成员来做到这一点:
err = db.DropTableIfExists(&Post{}, &Comment{}).Error
if err != nil {
// handle error
}
err = db.AutoMigrate(&Post{}, &Comment{}).Error
// Check error
err = db.Create(&Post{Title: "test1 title", Text: "text1"}).Error
// Check error
这是您问题的答案:
您没有将Comment
的一个切片传递给db.Model(&myPost).Related(&comments)
,并且期望返回一个切片,由于显而易见的原因,该切片将不起作用,因此您需要进行以下更改:
var comments Comment
到
var comments []Comment
答案 1 :(得分:0)