英文:
Making a Google App Engine datastore key from a string
问题
我正在将一个实体的"id"作为字符串传递到URL中,例如:
..../foo/234565
我想在以下查询中使用这个id:
//...我有一些代码从URL中获取stringId,并且我验证了它的工作
stringId = ....
theKey, err := datastore.DecodeKey(stringId)
q := datastore.NewQuery("Foo").Filter("__key__ =", theKey)
我得到的错误是:
proto: can't skip unknown wire type 7 for datastore.Reference
有没有一种简单的方法将stringId转换为"Key"类型?
英文:
I'm passing an entities "id" as a string on a URL, for example:
..../foo/234565
I want to use the id in the following query:
//...i hace some code that gets stringId from the URL, and I verified that it works
stringId = ....
theKey, err := datastore.DecodeKey(stringId)
q := datastore.NewQuery("Foo").Filter("__key__ =", theKey)
The error I'm getting:
proto: can't skip unknown wire type 7 for datastore.Reference
Is there a simple way to convert stringId into a "Key"?
答案1
得分: 3
c := appengine.NewContext(r)
//从提交的表单中获取实体ID。转换为int64
entity_id := r.FormValue("entity_id")
entity_id_int, err := strconv.ParseInt(entity_id, 10, 64)
if err != nil {
fmt.Fprint(w, "无法解析键")
return;
}
//根据Kind和实体ID(通过HTTP请求参数传递给我们)创建一个数据存储键。
key := datastore.NewKey(c, kind, "", entity_id_int, nil)
//加载此键表示的实体。
//我们必须先声明变量,然后进行Get操作,以便数据存储了解表示实体的结构。
var entity CustomStruct
datastore.Get(c, key, &entity)
英文:
c := appengine.NewContext(r)
//Retrieve the entity ID from the submitted form. Convert to an int64
entity_id := r.FormValue("entity_id")
entity_id_int, err := strconv.ParseInt(entity_id, 10, 64)
if err != nil {
fmt.Fprint(w, "Unable to parse key")
return;
}
//We manufacture a datastore key based on the Kind and the
//entity ID (passed to us via the HTTP request parameter.
key := datastore.NewKey(c, kind, "", entity_id_int, nil)
//Load the Entity this key represents.
//We have to state the variable first, then conduct the Get operation
//so the datastore understands the struct representing the entity.
var entity CustomStruct
datastore.Get(c, key, &entity)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论