【发布时间】:2016-10-26 15:03:53
【问题描述】:
我有一个具有以下架构的用户配置文件模型:
schema "user_profiles" do
field :birthday, Ecto.Date
field :gender, :string
field :first_name, :string
field :last_name, :string
field :description, :string
field :username, :string
# Associations
belongs_to :user, User
timestamps
end
我还有一个具有以下架构的位置模型:
schema "locations" do
field :name, :string
field :admin_1, :string
field :admin_2, :string
field :country, :string
field :country_abbreviation, :string
field :code, :string
field :latitude, :decimal
field :longitude, :decimal
timestamps
end
位置是像法国巴黎这样的城市。许多用户配置文件可以与同一位置相关联。但是位置并不需要知道用户配置文件的存在。
我想向用户配置文件架构添加位置关联。我不想用户 has_one 因为这种关系不是一对一的。我也不想将位置架构上的任何关联添加到用户配置文件中。
我查看了 Ecto 的文档,不知道如何表达这种关联。
我查阅了以下页面: https://hexdocs.pm/ecto/Ecto.Schema.html
我可能遗漏了一些基本的东西,但在问这个问题之前我确实尝试了很多东西。
【问题讨论】:
-
听起来你想要一个 many_to_many 关联。这意味着用户可以拥有多个位置,并且该位置可以属于多个用户。这通常是通过一个连接表来完成的,该表将被称为例如
location_profiles。这是一个更详细的链接:link -
@HarrisonLucas 感谢您的评论。我实际上只想为每个用户配置文件提供一个位置。一个位置可以“属于”多个用户配置文件。在数据库中,位置只是用户个人资料表上的一个外键。
-
啊,在这种情况下,为什么不直接做一个 Has_many 和 belongs_to 呢?例如。 Profilea 属于 locationa, Profileb 属于 locationa。因此,location has_many profile,而一个 profile 属于一个 location?
-
@HarrisonLucas 如果是这种情况,我是否必须在数据库中的位置表中添加外键?
-
我的答案见下文