簡體   English   中英

使用Go更新Google Appengine數據存儲區中的實體

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM