Reputation: 5175
I have an app using Go with this entity:
type Product struct {
Name string
Related []*datastore.Key
}
Is this possible to find all products that are related with a given key?
Upvotes: 1
Views: 564
Reputation: 1745
Is this possible to find all products that related with a given key?
As you're storing a slice of keys, this is not possible without retrieving all entities.
However, you could create a new kind (RelatedProducts
) which stores the related products (using the product as parent key).
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
}
Upvotes: 2