Data from association table

I’m making a simple webshop to get to know the phoenix framework (umbrella project).
I have a many-to-many relation between orders and products.
In the association table I have the columns ‘order_id’, ‘product_id’ and ‘quantity’.

I want to display the quantity next to each item in the shopping cart, but I just can’t figure out how to do it.

In my order_controller I have:

  def cart(conn, _params) do
    user = Guardian.Plug.current_resource(conn)
    order = OrderContext.get_currenct_order(user)
    render(conn, "cart.html", order: order)

In cart.html.heex I can loop over order.products and access attributes of product just fine (, product.price, …).

It’s pretty typical in e-commerce applications to promote the many-to-many association table to a full schema, called something like LineItem. Then the associations look like:

# in the Order schema:
has_many :line_items
has_many :products, through: :line_items

# in the LineItem schema:
belongs_to :order
belongs_to :product

# etc

Depending on your specific needs, you might also copy some fields from Product directly onto LineItem for safekeeping - for instance, you might preserve the product’s price value as of the time the LineItem was created so that future price changes don’t change historical orders.


Yep, that works.
Thanks a lot.