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

Jam0r's avatar
Level 8

Complex query, comparing sum of different tables

I have a base model with has a relation to two other models.

I'm calculating a balance and appending to the base model based on amounts recorded in the relationship models.

Both relationship models have fields named 'amount' which I total, and then subtract from each other, giving me a balance on the fly.

This works well as if and when a record in a relationship table is deleted, the balance gets updated on the fly without any extra calculations and query saves.

However I'd like to show a list of all base model records with a positive balance.

I can do this by getting the complete collection through eloquent and then filtering through the collection but this seems a waste of resources.

Is there another way?

I've tried getting my head around using a whereHas and a raw query but i'm confusing myself something rotten.

0 likes
0 replies

Please or to participate in this conversation.