1 回答
TA贡献1900条经验 获得超5个赞
是否可以找到与给定密钥相关的所有产品?
当您存储一片键时,如果不检索所有实体,则不可能做到这一点。
但是,您可以创建一种新类型(RelatedProducts),用于存储相关产品(使用产品作为父键)。
示例(未经测试)
type Product struct {
Name string
}
type RelatedProducts struct { // We store the the OriginalProduct as parent, so it is not needed as a property
Related *datastore.Key
}
// Create a new relation
func newRelation(c appengine.Context, productKey *datastore.Key, relatedProduct *datastore.Key) {
key := datastore.NewIncompleteKey(c, "RelatedProducts", productKey)
datastore.Put(c, key, &RelatedProduct{Related: relatedProduct})
}
// Get all related products
func getAllRelatedProducts(c appengine.Context, productKey *datastore.Key) []*datastore.Key{
var relatedProducts []RelatedProducts
// Query the relations
query := datastore.NewQuery("RelatedProducts").Ancestor(productKey)
query.GetAll(c, &relatedProducts)
// Loop over relatedProducts and append the data to keys
var keys []*datastore.Key
for i := range relatedProducts {
keys = append(keys, relatedProducts[i].Related)
}
return keys
}
- 1 回答
- 0 关注
- 201 浏览
添加回答
举报