【问题标题】:Ecto for Elixir: Foreign KeyElixir 的 Ecto:外键
【发布时间】: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 如果是这种情况,我是否必须在数据库中的位置表中添加外键?
  • 我的答案见下文

标签: elixir ecto


【解决方案1】:

一种解决方案是在配置文件将属于关系的两个模型之间建立一个简单的 has_many 和 belongs_to 关系。

这种关系意味着一个位置可以有多个与之关联的个人资料,而一个个人资料只能有一个位置。

例如

作品:

Profile1:伦敦 √

Profile2:伦敦 √

错误:

Profile1:伦敦 X

Profile1:法国 X

这就是你实施它的方式。

#web/models/location.ex
schema "location" do
  has_many :profiles, MyApp.Profile
end

#web/models/profile.ex
schema "profile" do
  belongs_to :location, MyApp.Location
end

然后在您的 profile_table 迁移中,您将拥有:

添加:location_id,引用(:locations)

您不需要位置模型的外键,只需要配置文件模型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    • 2021-04-14
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多