2011-10-26 162 views
0

我正在使用GAE,Go和數據存儲。我有以下結構:使用Go更新Google Appengine數據存儲中的實體

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

type Participant struct { 
    Email string 
    Seen datastore.Time 
} 

(對於那些想知道我保存Participants作爲切掉Key指針,因爲Go不自動取消引用的實體。)

現在我想找到一個特定的一個ParticipantEmail地址與知識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())。

由於提前,

回答

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())) 
}) 
1

我需要從fetchParticipants返回鍵以及打電話?

是的。然後調用 「FUNC認沽(C appengine.Context,關鍵*鍵,SRC接口{})(*鍵,os.Error)」

的Java和Python GAE實施顯得相當簡單一點(只是 在對象上調用put())。

可能是一個公平的聲明。 Go社區對「魔法」有強烈的偏見。在這種情況下,參與者結構有兩個你已經聲明的字段。在後臺添加密鑰將被視爲魔術。

相關問題