Hi guys,
I’m trying to build something similar to Twitter where users can follow other users. I’m not sure exactly how to properly create self-referencing schema in this case.
Migrations:
defmodule MyApp.Repo.Migrations.CreateUsers do
use Ecto.Migration
def change do
create table(:users) do
add :username, :string
end
end
end
defmodule MyApp.Repo.Migrations.CreateFollows do
use Ecto.Migration
def change do
create table(:followings) do
add :follower_id, references(:users, on_delete: :delete_all)
add :followed_id, references(:users, on_delete: :delete_all)
timestamps()
end
create index(:followings, [:follower_id, :followed_id], unique: true)
end
end
Schemas:
defmodule MyApp.User do
use Ecto.Schema
schema "users" do
field :username, :string
...
end
end
defmodule MyApp.Follow do
use Ecto.Schema
schema "followings" do
---
end
end
Can someone help me write the schemas properly using many_to_many please?