如何在Go中的App Engine上实现一对多?

kri*_*anp 18 google-app-engine go google-cloud-datastore

如何使用Go编程语言在Google App Engine上实现一对多?
例如,如果我有下面的结构,我如何将多个投票的关联存储到一个注释中?我会在Comment结构中使用一个数组(切片)键来投票,还是从投票结构中使用注释的一个键?

type Comment struct {
    Author  string
    Content string
    Date    datastore.Time
}

type Vote struct {
    User string
    Score int
}
Run Code Online (Sandbox Code Playgroud)

las*_*owh 17

当前版本的Go AppEngine SDK中允许使用字段的唯一类型如下:

  • 有符号整数(int,int8,int16,int32和int64),
  • 布尔,
  • 串,
  • float32和float64,
  • 任何类型的基础类型是上述预先声明的类型之一,
  • *键,
  • appengine.BlobKey,
  • []字节(长度最多1兆字节),
  • 任何上述切片(长度最多100个元素).

鉴于此,似乎有两种方法可以做到这一点.一种是保持一片键指向给定注释的投票.然而,对于任何相当受欢迎的评论,这可能会超过100元素限制.

另一种方法是在每个投票结构中存储注释的"指针",如下所示:

type Vote struct {
    User string
    Score int
    CommentKey *datastore.Key
}    

type Comment struct {
    Author  string
    Content string
    Date    datastore.Time
}
Run Code Online (Sandbox Code Playgroud)

然后当你去查询它时,你需要分两步完成.首先,你得到你感兴趣的评论(在这种情况下,只是第一个碰巧返回的评论).其次,您查询"指向"该评论的所有投票:

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
}
Run Code Online (Sandbox Code Playgroud)