Many to many with added field

Hello everyone.

I had Sale with many to many relationship with Item, join_through “sales_items” table. In “sales_items” table i added “quantity” field. My question is how to interact with this “quantity” field? These are my current schemas.

defmodule App.Sale do
  use App.Web, :model
  alias App.Item

  schema "sales" do
    many_to_many :items, Item, join_through: "sales_items"
  end
end

defmodule App.Item do
  use App.Web, :model
  alias App.Sale
  
  schema "items" do
    many_to_many :sales, Sale, join_through: "sales_items"
  end
end

Thank you.

1 Like

Finally i got this works. I added schema to join table and use has_many through: function. These are the latest schemas.

defmodule App.Sale do
  use App.Web, :model
  alias App.SaleItem

  schema "sales" do
    field :number, :integer
    has_many :sales_items, SaleItem, on_delete: :delete_all
    has_many :items, through: [:sales_items, :item]
  end
end

defmodule App.Item do
  use App.Web, :model
  alias App.SaleItem
  
  schema "items" do
    field :name, :string
    has_many :sales_items, SaleItem, on_delete: :delete_all
    has_many :sales, through: [:sales_items, :sale]
  end
end

defmodule App.SaleItem do
  use App.Web, :model
  alias App.Sale
  alias App.Item
  
  schema "sales_items" do
    belongs_to :sale, Sale
    belongs_to :item, Item
    field :quantity, :integer
  end
end

To get the data i used (simplified)

# preload the association
sale = Repo.get!(Sale, id) |> Repo.preload([:items])

sale.sales_items.quantity
sale.sales_items.item.name
# don't forget to loops the sales_items!

Hope this helps.

7 Likes