Many-to-Many releationship - How to update fields in join table using put_assoc

user <-> user_group <-> group

How can I populate tenant in user_group - With put assoc only user_id and group_id are getting auto updated in the join table (user_group) - How can I also include tenant_id

users =
      User
      |> tenant_filter(tenant)
      |> where([u], u.id in ^user_ids)
      |> Repo.all()
group
    |> cast(%{}, [])
    |> put_assoc(:users, users)


  schema "users_groups" do

    belongs_to :tenant, Tenant
    belongs_to :user, User
    belongs_to :group, Group

    timestamps()
  end
1 Like

It is not a many 2 many, it’s a has many & has many through, because the join table contains specific attributes (tenant_id). So You should treat the join table as an independant schema, and use it to join the 3 tables.

https://hexdocs.pm/ecto/Ecto.Schema.html#has_many/3

1 Like

Hi Anuj,

The way I think it should be implemented to have a separate schema for user and group. Also you will have migration for both. So you can create another schema and migration for user_group and there you can store the foreign key for both. This way you can use many-to-many relationship. Later if you want to add a tenant_id there I think you can do that.

Maybe this link can be helpful. Please refer this