jlzandrad's avatar

Add multiple addselect from the same table with different where statements

I ned to filter the taxable items, calculate tax and sum with the total price and if there is no taxes it should return 0.

with the code below it only returns the taxable items and ignores the second add select

$orders = Order::addSelect(['total_taxes' => Orderitem::whereColumn('order_id', 'orders.id')->where('taxable', true) ->selectRaw('sum(total_price * 0.06) as total_taxes')]) ->addSelect(['total_amount' => Orderitem::whereColumn('order_id', 'orders.id') ->selectRaw('sum(total_price) + total_taxes as total_amount')]) ->addSelect(['customer_name' => User::select('name') ->whereColumn('customer_id', 'users.id')]) ->with('status') ->get();

0 likes
1 reply
jlzandrad's avatar
jlzandrad
OP
Best Answer
Level 7

I think I got it

$orders = Order::addSelect(['total_taxes' => Orderitem::whereColumn('order_id', 'orders.id') ->selectRaw("SUM(CASE WHEN taxable = 1 THEN (total_price * 0.06)ELSE 0 END) AS total_taxes")]) ->addSelect(['total_amount' => Orderitem::whereColumn('order_id', 'orders.id') ->selectRaw('sum(total_price) + total_taxes as total_amount')]) ->addSelect(['customer_name' => User::select('name') ->whereColumn('customer_id', 'users.id')]) ->with('status') ->get();

Please or to participate in this conversation.