在虚拟表中添加关系

时间:2018-10-25 09:10:05

标签: elixir ecto

我有这些表,但它们不是persisting in the database。我用它们来测试一个库:

defmodule TestModel.Join do
  @moduledoc false
  use Ecto.Schema
  import Ecto.Changeset

  @fields [:public_name, :personal_name, :pass]
  @primary_key false

 schema "" do
  field(:public_name, :string, virtual: true)
  field(:pass, :integer, virtual: true)
  field(:personal_name, :string, virtual: true)
  belongs_to(:where, TestModel.Where, define_field: false, foreign_key: :first_name)
 end

 def changeset(data) when is_map(data) do
  %__MODULE__{}
  |> cast(data, @fields)
  |> apply_changes()
 end
end

belongs_to关系工作正常,但我还需要在where表中添加很多关系

defmodule TestModel.Where do
  @moduledoc false
  use Ecto.Schema
  import Ecto.Changeset

  @fields [:first_name, :last_name, :personal_id]
  @primary_key false

  schema "" do
    field(:first_name, :string, virtual: true)
    field(:personal_id, :integer, virtual: true)
    field(:last_name, :string, virtual: true)
  end

 def changeset(data) when is_map(data) do
   %__MODULE__{}
   |> cast(data, @fields)
   |> apply_changes()
 end
end

如何在此where模型中为联接表添加has_many relation

这行不通:

has_many(:joins, TestModel.Join)

谢谢

1 个答案:

答案 0 :(得分:0)

首先,您对belongs_to有疑问。 foreign_key应该specify the key in this table,而不是引用的那个。然后has_many将按预期工作:

# in Join schema
belongs_to(:where, TestModel.Where, foreign_key: :where_id)

# in Where schema
has_many(:joins, TestModel.Join, foreign_key: :where_id)

在所属表中没有外键的情况下,一对多关系就不可能。