使用Go更新Google Appengine数据存储区中的实体

时间:2011-10-26 14:46:10

标签: google-app-engine google-cloud-datastore go

我正在玩GAE,Go和数据存储区。我有以下结构:

type Coinflip struct {                                                                                                                                                                                                                      
  Participants []*datastore.Key
  Head         string
  Tail         string
  Done         bool
}

type Participant struct {
  Email string
  Seen  datastore.Time
}

(对于那些想知道我将Participants存储为Key指针切片的人,因为Go不会自动取消引用实体。)

现在,我想找到一个Participant,其中Email地址与知道Coinflip相关联。像这样(这是有效的):

coinflip, _ := find(key_as_string, context)
participants, _ := coinflip.fetchParticipants(context) /* a slice of Participant*/

var found *Participant
for i := 0; i < len(participants) && found == nil; i++ {
  if participants[i].Email == r.FormValue("email") {
    found = &participants[i]
  }
}
(*found).Seen = datastore.SecondsToTime(time.Seconds())

如何将*found保存到数据存储区?我显然需要密钥,但Participant结构和Key之间的耦合非常松散。

我不确定如何从这里开始。我还需要从fetchParticipants电话中返回密钥吗? Java和Python GAE实现看起来相当简单(只需在对象上调用put())。

提前致谢,

2 个答案:

答案 0 :(得分:1)

  

我还需要从fetchParticipants调用返回密钥吗?

是。然后调用“func Put(c appengine.Context,key * Key,src interface {})(* Key,os.Error)”

  

Java和Python GAE实现看起来相当简单(只是   在对象上调用put()。

可能是公平的陈述。 Go社区对“魔法”有很强的偏见。在这种情况下,Participant结构有两个您声明的字段。在后台添加密钥将被视为神奇。

答案 1 :(得分:0)

要与Go中的数据进行交互,请考虑使用我们的新库https://github.com/matryer/gae-records作为Active Record,数据对象包装在数据存储区周围。它为你排除了很多麻烦。

例如,它支持:

// create a new model for 'People'
People := gaerecords.NewModel("People")

// create a new person
mat := People.New()
mat.
 SetString("name", "Mat")
 SetInt64("age", 28)
 .Put()

// load person with ID 1
person, _ := People.Find(1)

// change some fields
person.SetInt64("age", 29).Put()

// load all People
peeps, _ := People.FindAll()

// delete mat
mat.Delete()

// delete user with ID 2
People.Delete(2)

// find the first three People by passing a func(*datastore.Query)
// to the FindByQuery method
firstThree, _ := People.FindByQuery(func(q *datastore.Query){
  q.Limit(3)
})

// build your own query and use that
var ageQuery *datastore.Query = People.NewQuery().
  Limit(3).Order("-age")

// use FindByQuery with a query object
oldestThreePeople, _ := People.FindByQuery(ageQuery)

// using events, make sure 'People' records always get
// an 'updatedAt' value set before being put (created and updated)
People.BeforePut.On(func(c *gaerecords.EventContext){
  person := c.Args[0].(*Record)
  person.SetTime("updatedAt", datastore.SecondsToTime(time.Seconds()))
})
相关问题