在虚拟表中添加关系

Adding relationship in virtual tables

我有这些 table 但它们不是 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 关系很好,但我还需要在 table

中添加很多关系
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 以加入 table?

这行不通:

has_many(:joins, TestModel.Join)

谢谢

首先,您对 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)

没有外键就不能建立一对多关系table。