doubushi0031 2019-09-13 02:15
浏览 32
已采纳

如何从数据存储中获取名称/密钥

Couldn't find any existing Go specific answer so creating a new one.

Our datastore consist of following columns/attributes

Name/ID Email UserID UserName

Now, I want to retrieve these values into my Go struct. Here is what i have written

type UserDetails struct {
    NameID    string
    Email     string `datastore:"Email"`
    UserID    string `datastore:"UserID"`
    UserName  string `datastore:UserName`
}

Now, when i am fetching this entity (based on kind), I am manually setting the NameID i.e.,

func (c DataStoreClient) GetUserDetailsByOrg(ctx context.Context, orgName string) ([]*UserDetails, error) {
    var userDetails []*UserDetails
    q := datastore.NewQuery(userDetailsKind).
        Namespace(orgName)
    keys, err := c.client.GetAll(ctx, q, &userDetails)
    for i, key := range keys {
        userDetails[i].NameID = key.Name
    }
    return userDetails, err
}

Now, the question that i want to ask that is this the correct approach to retrieve Name/ID or can i retrieve it by specifying datastore:Name/ID in struct?

  • 写回答

2条回答 默认 最新

  • dpp66953 2019-09-13 02:48
    关注

    Implement the KeyLoader interface to set the field during entity load.

    type UserDetails struct {
        NameID   string `datastore:"-"`
        Email    string `datastore:"Email"`
        UserID   string `datastore:"UserID"`
        UserName string `datastore:UserName`
    }
    
    func (ud *UserDetails) LoadKey(k *datastore.Key) error {
        ud.NameID = k.Name
        return nil
    }
    
    func (ud *UserDetails) Load(ps []datastore.Property) error {
        return datastore.LoadStruct(ud, ps)
    }
    
    func (ud *UserDetails) Save() ([]datastore.Property, error) {
        return datastore.SaveStruct(ud)
    }
    

    Use it like this:

    func (c DataStoreClient) GetUserDetailsByOrg(ctx context.Context, orgName string) ([]*UserDetails, error) {
        var userDetails []*UserDetails
        q := datastore.NewQuery(userDetailsKind).
            Namespace(orgName)
        _, err := c.client.GetAll(ctx, q, &userDetails)
        return userDetails, err
    }
    

    The approach in the question works. The advantage of the KeyLoader implementation is that it saves a couple of lines of code wherever the application queries for or gets an entity.

    Set the NameID datastore name to "-" so that the property loader and saver ignores the field.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效