0

I'm using Laravel 9 to perform a withSum on my relationship credit_transactions. I need to return all PersonalAccessToken models where the credit_balance is less than a certain value, for example, 50 - this way my application knows whether to top up their balance.

This is my query:

/** * Get all keys that can be auto topped-up */ public function getEnabledTopUpKeys() { return PersonalAccessToken::whereNotNull('region_code') ->where('auto_topup_enabled', true) ->whereNotNull('auto_topup_slug') ->withSum('credit_transactions AS credit_balance', 'delta') ->where('credit_balance', '<', 100) ->get(); } 

This doesn't work, it throws an error:

Unknown column 'credit_balance' in 'where clause'

What am I missing to perform this?

1 Answer 1

1

withSum generates a sub query, so it can't be used in a where query. But that sub query creates an on-the-fly column that you can add to your query. For instance,

Order::withSum('orderItems', 'quantity') ->take(5) ->get(); 

creates an aliased column named order_items_sum_quantity, that I can then use as a having query:

Order::withSum('orderItems', 'quantity') ->having('order_items_sum_quantity', '>', 100) ->take(5)->get(); 

In your case, you may be getting a column named credit_balance_sum_delta that you can use in your query:

PersonalAccessToken::whereNotNull('region_code') ->where('auto_topup_enabled', true) ->whereNotNull('auto_topup_slug') ->withSum('credit_transactions AS credit_balance', 'delta') ->having('credit_balance_sum_delta', '<', 100) ->get(); 

If that isn't quite the correct column name, try getting one record without the having line, then check the results to find out the column name

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.