Adding relationship in virtual tables

I have these tables and they are not persist in the database. I used 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 as has_many expect 3 arguments

 has_many(:joins, TestModel.Join)

Thanks

Remove @primary_key false from both models And then try

@leaf: First of all you should not use belongs_to, has_many, has_one and schema/2 for virtual tables. Instead of them use:

  1. schema/2 -> embedded_schema/1
  2. belongs_to/3 and has_one/3 -> embeds_one/3
  3. has_many/3 -> embeds_many/3

I strongly recommend to read Working with Ecto associations and embeds

1 Like