Please format your code (you can edit the post) https://help.github.com/articles/creating-and-highlighting-code-blocks/
Sep 15, 2022
8
Level 1
Laravel raw query related field calculation
I wanna filter customers based on balance (which comes from the related 'ledgers' eloquent model table which has 'customer_id', 'amount' and 'type ' fields (type=1 credit and type =2 debit)) my codes are as
// Balance Filter
if ($this->min_balance) {
$this->customers = Customer::whereHas('ledgers', function ($query) {
$query->select(DB::raw('SUM( (SUM(amount) WHERE type = 1 AS total_credits) - (SUM(amount) WHERE type = 2 AS total_debits) ) >= ' . $this->min_balance));
})->get();
} else {
$this->reloadCustomers();
}
but I am getting error
"SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE type = 1 AS total_credits) - (SUM(amount) WHERE type = 2 AS total_debits)' at line 1 (SQL: select * from `customers` where exists (select SUM( (SUM(amount) WHERE type = 1 AS total_credits) - (SUM(amount) WHERE type = 2 AS total_debits) ) >= 12 from `ledgers` where `customers`.`id` = `ledgers`.`customer_id`))"
any help appreciated.
Please or to participate in this conversation.