Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lovatt's avatar

Pivot table sums?

How would i do calculations on data within a pivot table?

I have 3 tables:

Orders (id, date, customer_id) Order_Product (id, order_id, product_id, quantity, term, sell_price, buy_price) and Products (id, name)

I have setup a many to many relationship using the Order_product pivot table.

I'm stuck with how i would go about calculating the total contract value for example (sell_price * quantity * term) and returning this to the view?

0 likes
4 replies
lovatt's avatar

Anybody? Am i barking up the wrong tree?

Ozan's avatar

Just be patient nobody gets answer before 1-2 hours.

Ozan's avatar

You will need to select a row and access the pivot.

foreach($orders->products as $product) {
    $total[$product->id] = $product->pivot->sell_price * $product->pivot->quantity * $product->pivot->term;
}

Please or to participate in this conversation.