Skip to content
Advertisement

Laravel get sum of related table’s columns with eloquent

I’m having some trouble calculating the price of my carts with eloquent, here are my tables:

JavaScript

One cart can have multiple cart_products, and each cart_products have one product associated

I’m making the request from the Cart Model, I’m trying to get the total price of the cart (cart_products.quantity * products.price).

Here is my query:

JavaScript

When I’m doing that, I do get the expected result but all the carts that doesn’t contains product are excluded, I would like them to be included.

How could I include them ? Or is there a better way to do it (I saw withCount method but I couldn’t make it work properly) ?

Advertisement

Answer

Another way would be to setup a virtual relation in your cart model and calculate your cart price like

JavaScript

To get price data for your carts your can query as

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement