中间模型具有两个外键:文件结构?

huangapple go评论90阅读模式
英文:

Intermediate model with two foreign keys: file structure?

问题

目标是创建一个中间模型(user_product),它有两个外键:userproduct

我们能否通过在外部文件中使用用户和产品结构体(某种方式)来实现这一目标,还是必须将它们与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.

huangapple
  • 本文由 发表于 2017年7月12日 17:29:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/45053785.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定