如何在Go编程语言的Google App Engine上实现一对多
type Comment struct {
Author string
Content string
Date datastore.Time
}
type Vote struct {
User string
Score int
}
如何在Go编程语言的Google App Engine上实现一对多
type Comment struct {
Author string
Content string
Date datastore.Time
}
type Vote struct {
User string
Score int
}
Go AppEngine SDK当前版本中允许的字段类型只有as follows:
鉴于此,似乎有两种方法可以做到这一点.一种是维护一段关键字,以指向给定 comments 的投票.然而,这很可能会违反任何相当流行的 comments 的100个元素的限制.
另一种方法是在每个投票 struct 中存储指向注释的"指针",如下所示:
type Vote struct {
User string
Score int
CommentKey *datastore.Key
}
type Comment struct {
Author string
Content string
Date datastore.Time
}
然后,当你go 查询它时,你需要分两步进行.首先,你会得到你感兴趣的 comments (在本例中,只是第一条碰巧被返回的 comments ).其次,查询所有"指向"该 comments 的投票:
q := datastore.NewQuery("Comment").Limit(1)
comments := make([]Comment, 0, 1)
var err os.Error
var keys []*datastore.Key
if keys, err = q.GetAll(c, &comments); err != nil {
// handle the error
}
comment := comments[0]
vq := datastore.NewQuery("Vote").Filter("CommentKey=", keys[0])
votes := make([]Vote, 0, 10)
if _, err := vq.GetAll(c, &votes); err != nil {
// handle the error
}