英文:
How to query for entity with key whose ancestor is not known?
问题
A
是B
的祖先
type A struct {}
type B struct {}
无论祖先是否存在,我应该如何搜索stringID
为stringID
的B
?(B
和祖先A
甚至可能不存在)
ctx := appengine.NewContext(r)
a := ??? // 'A'可能不存在,那我在这里该怎么办?
k := datastore.NewKey(ctx, "B", "stringID", 0, a)
e := new(B)
if err := datastore.Get(ctx, k, e); err != nil {
http.Error(w, err.Error(), 500)
return
}
英文:
A
is ancestor of B
type A struct {}
type B struct {}
How would I search for B
whose string ID is stringID
, regardless of ancestor? (B and ancestor A may not even exist)
ctx := appengine.NewContext(r)
a := ??? // 'A' may not exist, so what do I do here?
k := datastore.NewKey(ctx, "B", "stringID", 0, a)
e := new(B)
if err := datastore.Get(ctx, k, e); err != nil {
http.Error(w, err.Error(), 500)
return
}
答案1
得分: 2
祖先实体可能不存在,但其ID或名称必须已知。否则,您将无法为子实体创建唯一键。请注意,A的子实体和B的子实体可能具有相同的ID或名称。
还要注意,您可以删除一个实体并创建一个新实体,但是一旦实体创建后,您无法更改其父实体。
英文:
Ancestor entity may not exist, but its ID or Name must be known. Otherwise you will not be able to create a unique key for a child entity. Note that child of A and child of B may have the same ID or Name.
Also note that you may delete one entity and create a new one, but you cannot change the parent of an entity once it's created.
答案2
得分: 1
你可以在不实际创建实体a
的情况下为a
创建一个键(只有在调用datastore.Put()
时才会创建实体)。然后,你可以使用该键来创建b
(或者只是它的键,如果你希望如此)。
至于查询方面:你可以对所有B类型的实体进行一个仅返回键的查询,然后对每个键检查键的字符串ID是否与你所需的stringID
匹配。你可以获得多个结果-对于具有不同祖先的实体,字符串ID仅在相同的祖先(或根本没有祖先)下是唯一的。
英文:
You can create a key for a
without actually creating the a
entity (the entity is only created when you call datastore.Put()
). You can then use that key to create b
(or just its key, if so you desire).
As for the query aspect: you could do a keys-only query for all entities of B type, then for each key check if the key's stringID matches your desired stringID
. You can get multiple results - for entities with different ancestors - stringID is unique only for the same ancestor (or no ancestor at all).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论