如何为has_one / belongs_to_many关联定义Elixir Ecto模式?

作者在https://elixirschool.com/en/lessons/ecto/associations/#belongs-tohas-one对“属于/拥有一个”协会的解释中写道:

  

假设电影有一个发行商,例如Netflix是   他们的原始电影《光明》的发行人。

     

...

     

...分发服务器架构应使用belongs_to / 3宏以允许   我们打电话给distributor.movi​​e,并查找分销商的关联   电影使用此外键。

     

...

     

has_one / 3宏功能与has_many / 3宏一样。它用   相关架构的外键以查找并公开电影的外键   分销商。这将使我们能够调用movie.distributor。

以下是其示例的架构:

defmodule Example.Distributor do
  use Ecto.Schema

  schema "distributors" do
    field :name,:string
    belongs_to :movie,Example.Movie
  end
end

defmodule Example.Movie do
  use Ecto.Schema

  schema "movies" do
    field :title,:string
    field :tagline,:string
    has_many :characters,Example.Character
    has_one :distributor,Example.Distributor # I'm new!
  end
end

José Valimhttp://blog.plataformatec.com.br/2015/08/working-with-ecto-associations-and-embeds/写:

  

has_one / 3和belongs_to / 3之间的区别在于   键总是在调用belongs_to / 3的模式中定义。

因此,通过在Distributor模式中使用belongs_to / 3,可以在该模式中定义一个外键,从而在此示例中将单个分发者限制为单个影片。 (这一点已通过示例作者的“ ...允许我们调用distributor.movi​​e并使用此外键查找与发行商相关的电影来证实。”

如果我要让一部电影有一个发行人,但要一个发行人有一部或更多电影,我将如何定义模式?

diegod3433 回答:如何为has_one / belongs_to_many关联定义Elixir Ecto模式?

您将其反转。

如果电影只有一个发行者,则将外键放在其模式中。

然后,当您需要为一个特定的发行商查找电影时,您只需查找具有distributor_id外键并引用发行人ID的所有电影。

defmodule Example.Movie do
  use Ecto.Schema

  schema "movies" do
    field :title,:string
    field :tagline,:string
    has_many :characters,Example.Character
    belongs_to :distributor,Example.Distributor
  end
end
defmodule Example.Distributor do
  use Ecto.Schema

  schema "distributors" do
    field :name,:string
    has_many :movies,Example.Movie
  end
end
本文链接:https://www.f2er.com/3126578.html

大家都在问