英文:
Intermediate model with two foreign keys: file structure?
问题
目标是创建一个中间模型(user_product),它有两个外键:user和product。
我们能否通过在外部文件中使用用户和产品结构体(某种方式)来实现这一目标,还是必须将它们与UserProduct放在同一个文件中,就像文档中所示?
目前,将它们放在外部并在UserProduct中导入它们会导致导入循环错误。
结构如下:
app/
models/
product.go
user.go
user_product.go
问题在于,如果我在user_product
中使用import "github.com/somehow/somehow/models"
导入product.go
,显然它也会导入user_product
,而user_product
又导入models
,依此类推。
英文:
The goal is to create an intermediate model (user_product) which has two foreign keys: user and product.
Can we achieve this with user and product structs in external files (somehow) or have we to put them in the same file with UserProduct one, like in the docs?
At this time, putting them externally and importing them in UserProduct will throw an import cycle error, of course.
The structure:
app/
models/
product.go
user.go
user_product.go
The problem is that if I import product.go
in user_product
with import "github.com/somehow/somehow/models"
, obviously it imports also user_product
which imports models
and so on.
答案1
得分: 0
所有文件都属于同一个包(文件顶部必须有相同的包名!)。
你不需要导入属于同一个包(同一个文件夹)的其他文件。
只需删除导入语句,你仍然可以访问user_product中的product,反之亦然。
英文:
All files in one folder belong to the same package (must have the same package name at the top of the file!).
You do not need to import other files that belong to the same package (the same folder).
Just remove the import and you should still have access to product in user_product and vice versa.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论