Ecto for Elixir:外键

Ecto for Elixir: Foreign Key

我有一个具有以下架构的用户配置文件模型:

  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

我可能遗漏了一些基本的东西,但在问这个问题之前我确实尝试了很多东西。

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

这种关系意味着一个位置可以有多个关联的配置文件,而一个配置文件只能有一个位置。

例如

Works:

Profile1:London √

Profile2:London √

Wrong:

Profile1:London X

Profile1:France 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 迁移中,您将拥有:

add :location_id, references(:locations)

位置模型不需要外键,只有个人资料模型。