根据切片属性过滤实体

时间:2012-12-22 03:46:39

标签: google-app-engine google-cloud-datastore go

我有一个使用Go与此实体的应用程序:

type Product struct {
  Name string
  Related []*datastore.Key
}

是否可以找到与给定密钥相关的所有产品?

1 个答案:

答案 0 :(得分:2)

  

是否可以找到与给定密钥相关的所有产品?

当您存储一片密钥时,如果不检索所有实体,这是不可能的。

但是,您可以创建一种新类型(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
}