英文:
How do I create associations in gRPC proto files?
问题
我可能走错了方向,但我想要定义两个或多个结构体(消息)之间的关系。
以StackOverflow为例,假设我有一个用于对标签执行CRUD操作的LabelService。我还有一个QuestionService,其中一个Question可以有多个Label。假设我还有一个UserService,一个User也可以附加标签。
# label.proto
service LabelService {
    rpc CreateLabel() returns();
    ...etc
}
message Label {
   string text = 1;
}
但现在我想创建我的QuestionService和Question消息。我是否需要以某种方式关联这两个文件,还是这种关联是在Go代码中完成的?
# question.proto
service QuestionService {
    rpc CreateQuestion() returns();
    ...etc
}
message Question {
   string text = 1;
   repeated Label labels = 2; // <-- 如何实现这个?
}
# user.proto
service UserService {
    rpc CreateQuestion() returns();
    ...etc
}
message User {
   string name = 1;
   repeated Label labels = 2; // <-- 如何实现这个?
}
我觉得我感到困惑是因为对于REST API和使用gorm.io这样的库,我会在结构体中设置关联,并让gorm.io创建表格。
英文:
I'm might be going about it the wrong way, but I want to define a relationship between two or more structs (messages).
Using StackOverflow as an example, let's say I had a LabelService for CRUD actions on labels. I also have a QuestionService where a Question can have Labels. Let's also assume I have a UserService and a User can also have labels attached
# label.proto
service LabelService {
    rpc CreateLabel() returns();
    ...etc
}
message Label {
   string text = 1;
}
But now I want to create my QuestionService and Question message. Do I associate the two files some how or is this level of association done in the go code?
# question.proto
service QuestionService {
    rpc CreateQuestion() returns();
    ...etc
}
message Question {
   string text = 1;
   repeat Label labels = 2 # <-- how to do this?
}
# user.proto
service UserService {
    rpc CreateQuestion() returns();
    ...etc
}
message User {
   string name = 1;
   repeat Label labels = 2 # <-- how to do this?
}
I think I'm confused because for REST APIs and using gorm.io for example, I would setup the associations in the structs and have gorm.io create the tables.
答案1
得分: 5
从文档中可以看到:
在你的question.proto文件中,只需简单地添加一个import语句来引入user.proto文件,就像引入其他标准的proto定义(如timestamp和duration)一样:
import "user.proto";
import "google/protobuf/timestamp.proto";
import "google/protobuf/duration.proto";
请注意,这里的user.proto是你自己的文件路径,你需要根据实际情况进行替换。
英文:
From the docs:
import "myproject/other_protos.proto";
so just simply add an import in your question.proto to your user.proto. It's no different than when importing other standard proto definitions like timestamp and duration:
import "google/protobuf/timestamp.proto";
import "google/protobuf/duration.proto";
答案2
得分: 2
你已经在question.proto中导入了user.proto吗?
在question.proto中:
import "user.proto" <- 我认为你可以使用Label labels。
英文:
Did you already import user.proto in question.proto?
in question.proto
import "user.proto" <- i think you can use Label labels
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论