英文:
Filter entities based on a slice property
问题
这是可能的,你可以使用以下代码来找到所有与给定键相关的产品:
func findRelatedProducts(key *datastore.Key) ([]*Product, error) {
query := datastore.NewQuery("Product").Filter("Related =", key)
var products []*Product
_, err := query.GetAll(ctx, &products)
if err != nil {
return nil, err
}
return products, nil
}
在上面的代码中,我们使用datastore.NewQuery
来创建一个查询,然后使用Filter
方法来过滤与给定键相关的产品。最后,我们使用GetAll
方法来执行查询并将结果存储在products
切片中。如果发生错误,我们将返回nil
和错误信息。否则,我们将返回找到的产品切片。
英文:
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?
答案1
得分: 2
这是可能的,你可以创建一个新的实体类型(RelatedProducts),它存储与给定关键字相关的产品(使用产品作为父键)。
示例(未经测试)
type Product struct {
Name string
}
type RelatedProducts struct { // 我们将原始产品作为父键存储,因此不需要作为属性
Related *datastore.Key
}
// 创建新的关系
func newRelation(c appengine.Context, productKey *datastore.Key, relatedProduct *datastore.Key) {
key := datastore.NewIncompleteKey(c, "RelatedProducts", productKey)
datastore.Put(c, key, &RelatedProduct{Related: relatedProduct})
}
// 获取所有相关产品
func getAllRelatedProducts(c appengine.Context, productKey *datastore.Key) []*datastore.Key{
var relatedProducts []RelatedProducts
// 查询关系
query := datastore.NewQuery("RelatedProducts").Ancestor(productKey)
query.GetAll(c, &relatedProducts)
// 遍历relatedProducts并将数据追加到keys中
var keys []*datastore.Key
for i := range relatedProducts {
keys = append(keys, relatedProducts[i].Related)
}
return keys
}
英文:
> 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).
Example (Not tested)
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论