首页 文章

AppEngine数据存储Golang:获取查询结果的祖先

提问于
浏览
1

是否可以获取查询结果的祖先密钥?根据数据存储文档(https://cloud.google.com/appengine/docs/go/datastore/reference#Query.Run),query.Run()结果只有一个Cursor()和一个Next()函数,它们都不会引导您进入祖先 . 看起来这应该是's in scope, unless the mechanics of Datastore prevent it. Is it up to the developer to write the ancestor into a property (with a matching kind) on the child (if we'愿意为此付出代价的信息?

1 回答

  • 2

    如果查询返回结果,则祖先包含在实体Key中 .

    实例键由Iterator.Next()返回,例如:

    func (t *Iterator) Next(dst interface{}) (*Key, error)
    

    从密钥中,使用Key.Parent()方法获取祖先 .

    看这个例子:

    query := datastore.NewQuery("MyEntity")
    
    e := MyEntity{}
    for i := query.Run(ctx); ; {
        if k, err = t.Next(&te); err == nil {
            log.Infof("Ancestor / parent key: %v", k.Parent())
        }
    }
    

    请注意,祖先存储在datastore.Query中,但不会导出:

    type Query struct {
        ancestor *Key
        // ...
    }
    

    并且Query.Run()返回的datastore.Iterator包含 Query ,但它也未被导出:

    type Iterator struct {
        // q is the original query which yielded this iterator.
        q *Query
        //...
    }
    

    因此,您无法访问这些结构字段,您最好的选择是结果中的实际实体(或者更确切地说是其键) .

相关问题