英文:
Modeling N to N associations in Go on the App Engine
问题
我正在尝试使用Google App Engine在Go中编写一个Web应用程序,并且我对使用数据存储建模关系有一个问题。
我知道在Python中,我可以使用db.referenceProperty()来建模关系。但是我似乎无法弄清楚如何使用Go的API建立类似的关联。
有人在这方面有过成功的经验吗?
英文:
I'm attempting to write a webapp in Go using the Google App Engine, and I have a question about modeling relationships using the datastore.
I know in Python I would be able to model a relationship using a db.referenceProperty(). What I can't seem to figure out is how to make a similar association using the Go APIs.
Has anyone had any luck with this?
答案1
得分: 5
你可以在实体中使用Key作为属性:http://code.google.com/appengine/docs/go/datastore/reference.html
类似这样(我不懂Go,请谅解):
type Employee struct {
Name string
Boss *Key
}
employee := Employee{
Name: "John Doe",
Boss: key // 指向其他实体的键
}
英文:
You can use Key as a property in the entity: http://code.google.com/appengine/docs/go/datastore/reference.html
Something like this (I don't know Go so bear with me):
type Employee struct {
Name string
Boss *Key
}
employee := Employee{
Name: "John Doe",
Boss: key // a key to some other entity
}
答案2
得分: 2
Peter,你肯定是在正确的轨道上。我认为我已经弄清楚了这个问题。我还没有真正测试过这个,但在数据存储查看器中看起来是正确的。我现在的代码看起来像这样(忽略了示例中的错误检查):
type Boss struct {
Name, Uuid string
}
type Employee struct {
Name, Uuid string,
Boss *datastore.Key
}
boss := &Boss {
Name: "Pointy Haired Boss",
Uuid: <<some uuid>>,
}
dilbert := &Employee {
Name: "Dilbert",
Uuid: <<some uuid>>,
boss: nil,
}
datastore.Put(context, datastore.NewIncompleteKey(context, "Boss", nil), bossman)
query := datastore.NewQuery("Boss").Filter("Uuid =", bossMan)
for t := query.Run(ctx); ; {
var employee Employee
key, err := t.Next(&employee)
if err == datastore.Done {
break
}
if err != nil {
fmt.Fprintf(w, "Error %s", err)
}
dilbert.Boss = key
}
datastore.Put(context, datastore.NewIncompleteKey(context, "Employee", nil), dilbert)
英文:
Peter, you were definitely on the right track. I think I've figured this out. I haven't really tested this, but it appears to be right in the datastore viewer. What I have right now looks like this (ignoring error checking for the example):
type Boss struct {
Name, Uuid string
}
type Employee struct {
Name, Uuid string,
Boss *datastore.Key
}
boss := &Boss {
Name: "Pointy Haired Boss",
Uuid: <<some uuid>>,
}
dilbert := &Employee {
Name: "Dilbert",
Uuid: <<some uuid>>,
boss: nil,
}
datastore.Put(context, datastore.NewIncompleteKey(context, "Boss", nil), bossman)
query := datastore.NewQuery("Boss").Filter("Uuid =", bossMan)
for t := query.Run(ctx); ; {
var employee Employee
key, err := t.Next(&employee)
if err == datastore.Done {
break
}
if err != nil {
fmt.Fprintf(w, "Error %s", err)
}
dilbert.Boss = key
}
datastore.Put(context, datastore.NewIncompleteKey(context, "Employee", nil), dilbert)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论