[英]Updating entity in Google Appengine datastore with 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
,该Participant
具有与已知Coinflip
关联的特定Email
地址。 像这样(可行):
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()
)。
提前致谢,
我还需要从fetchParticipants调用中返回密钥吗?
是。 然后调用“ func Put(c appengine.Context,键* Key,src接口{})(*键,os.Error)”
Java和Python GAE的实现似乎要简单得多(只需在对象上调用put()即可)。
可能是一个公正的声明。 Go社区强烈反对“魔术”。 在这种情况下,参与者结构具有两个已声明的字段。 在后台为其添加密钥将被视为魔术。
要与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()))
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.