Nested many-to-many relationship

I have the following schemas

  schema "wishlists" do
    belongs_to(:user, User)
    many_to_many(:products, Product, join_through: ProductWishlist)

    timestamps()
  end
  schema "products" do
    ...
    many_to_many(:wishlists, Wishlist, join_through: ProductWishlist)

    timestamps()
  end
  schema "products_wishlists" do
    belongs_to(:product, Product)
    belongs_to(:wishlist, Wishlist)
    many_to_many(:filters, ProductFilter, join_through: ProductFilterWishlist)

    timestamps()
  end
  @primary_key false
  schema "products_filters_wishlists" do
    belongs_to(:products_filters, ProductFilter, foreign_key: :product_filter_id)
    belongs_to(:products_wishlists, ProductWishlist, foreign_key: :product_wishlist_id)

    field(:quantity, :integer)

    timestamps()
  end

can I somehow preload the filters from products_wishlist?
something like (incorrect code following:

Repo.get!(Wishlist, id)
    |> Repo.preload(:filters) <-------

Is there any possible way to not use many-to-many at all? I’ve got done that path and all it gave me was pain. Ended-up just simplifying it with one-to-many.

has_many :product_wishlists, ProductWishlist
has_many :filters, through: [:product_wishlists, :filters]

Add those to your wishlists schema.

1 Like

Do I need to replace many_to_many also in products schema?

What changes do I need in the repo migrations? Currently my migrations file looks like this:

  def change do
    create table(:wishlists) do
      add(:user_id, references(:users, on_delete: :nothing))

      timestamps()
    end

    create table(:products_wishlists) do
      add(:product_id, references(:products))
      add(:wishlist_id, references(:wishlists))

      timestamps()
    end
  end

No, just add those lines. You can have many_to_many and has_many relationships side by side.

Thanks, that did the trick.