更新从appengine .GetAll获取的实体并保存到数据存储中。

huangapple go评论68阅读模式
英文:

Update entity from appengine .GetAll and save to datastore

问题

我有一个模型:

type UserProfile struct {
    UserID         string    `datastore:"user_id" json:"user_id,omitempty"`
    Username       string    `datastore:"username" json:"username,omitempty"`
    StripUsername  string    `datastore:"strip_username" json:"strip_username,omitempty"`
    Email          string    `datastore:"email" json:"email,omitempty"`
    LoginType      string    `datastore:"login_type" json:"login_type,omitempty"`
    CurrentSession string    `datastore:"current_session" json:"current_session,omitempty"`
    FBAcessToken   string    `datastore:"fb_access_token" json:"fb_access_token,omitempty"`
    Created        time.Time `datastore:"created" json:"-"`
}

然后我执行一个 .GetAll 来填充它:

// 这里省略了一些步骤

var userProfiles []UserProfile
q.GetAll(c, &userProfiles)

假设我想修改其中一个实体:

userProfiles[0].Email = "test@example.com"

我知道我想要像这样 Put 该实体:

k = datastore.Put(c, k, userProfiles[0])

如何从 userProfiles[0] 获取初始键以便调用 Put

英文:

I have a model:

type UserProfile struct {
UserID         string    `datastore:"user_id" json:"user_id,omitempty"`
Username       string    `datastore:"username" json:"username,omitempty"`
StripUsername  string    `datastore:"strip_username" json:"strip_username,omitempty"`
Email          string    `datastore:"email" json:"email,omitempty"`
LoginType      string    `datastore:"login_type" json:"login_type,omitempty"`
CurrentSession string    `datastore:"current_session" json:"current_session,omitempty"`
FBAcessToken   string    `datastore:"fb_access_token" json:"fb_access_token,omitempty"`
Created        time.Time `datastore:"created" json:"-"`
}

And I perform a .GetAll to populate it:

// Skip a few steps here

var userProfiles []UserProfile
q.GetAll(c, &userProfiles)

Say I want to modify one of those entities:

userProfile[0].Email = "test@example.com"

I know I want to Put that entity like so:

k = datastore.Put(c, k, userProfile[0])

How do I get that initial key from userProfile[0] to call Put with?

答案1

得分: 3

GetAll 返回的是键(keys):

var userProfiles []UserProfile
keys, err := q.GetAll(c, &userProfiles)
if err != nil {
    // 处理错误
}

使用从 GetAll 返回的键来更新实体(entities):

userProfile[0].Email = "test@example.com"
_, err = datastore.Put(c, keys[0], userProfile[0])
if err != nil {
    // 处理错误
}
英文:

GetAll returns the keys:

var userProfiles []UserProfile
keys, err := q.GetAll(c, &userProfiles)
if err != nil {
    // handle error
}

Update entities using the keys returned from GetAll:

userProfile[0].Email = "test@example.com"
_, err = datastore.Put(c, keys[0], userProfile[0])
if err != nil {
    // handle error
}

huangapple
  • 本文由 发表于 2015年3月16日 10:26:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/29068749.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定