Search code examples
elixirecto

Adding relationship in virtual tables


I have these tables and they are not persisting in the database. I use them to test a library:

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

The belongs_to relationship works fine but I also need to add has many relationship in the where 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

How can I add has_many relation for join table in this where model?

This won’t work:

has_many(:joins, TestModel.Join)

Thanks


Solution

  • You have issues with belongs_to in the first place. foreign_key should specify the key in this table, not in the referenced one. Then has_many would work as expected:

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

    One cannot has one-to-many relationship without a foreign key in the belonging table.