我有一个查询,我试图将其转换为laravel查询构建器样式。 但是我无法成功。
这是我的查询
SELECT
count(*)
FILTER (WHERE order_status_id IN (5, 4, 15)) AS ready_for_delivery,
count(*)
FILTER (WHERE order_status_id IN (6)) AS out_for_delivery,
count(*)
FILTER (WHERE order_status_id IN (4, 10, 9, 12, 7)) AS completed_order,
count(*)
FILTER (WHERE order_status_id IN (11, 16, 17, 13)) AS waiting_for_cancellation_return_change
FROM order_item_histories;
这是我从http://www.midnightcowboycoder.com/得到的,显然不起作用。但这是一个起点
DB::table('order_item_histories')
->selectSub('count', 'ready_for_delivery')
->selectSub('FILTER', 'ready_for_delivery')
->selectSub('count', 'out_for_delivery')
->selectSub('FILTER', 'out_for_delivery')
->selectSub('count', 'completed_order')
->selectSub('FILTER', 'completed_order')
->selectSub('count', 'waiting_for_cancellation_return_change')
->selectSub('FILTER', 'waiting_for_cancellation_return_change')
->get();
此查询有效,但它只是原始的。我知道没有害处,但是......
$aa = DB::table('order_item_histories')
->select(DB::raw('count(*)
FILTER (WHERE order_status_id IN (5, 4, 15)) AS ready_for_delivery,
count(*)
FILTER (WHERE order_status_id IN (6)) AS out_for_delivery,
count(*)
FILTER (WHERE order_status_id IN (4, 10, 9, 12, 7)) AS completed_order,
count(*)
FILTER (WHERE order_status_id IN (11, 16, 17, 13)) AS waiting_for_cancellation_return_change'))
->get();
答案 0 :(得分:1)
DB::table('order_item_histories')
->selectRaw('count(*) FILTER (WHERE order_status_id IN (?, ?, ?)) AS ready_for_delivery', [5, 4, 15])
->selectRaw('count(*) FILTER (WHERE order_status_id IN (?)) AS out_for_delivery', [6])
->selectRaw('count(*) FILTER (WHERE order_status_id IN (?, ?, ?, ?, ?)) AS completed_order', [4, 10, 9, 12, 7])
->selectRaw('count(*) FILTER (WHERE order_status_id IN (?, ?, ?, ?)) AS waiting_for_cancellation_return_change', [11, 16, 17, 13])
->get();
答案 1 :(得分:1)
尝试使用case
代替filter
$users = DB::table('order_item_histories')
->select(DB::raw('SUM(CASE WHEN order_status_id IN (5, 4, 15) THEN 1 ELSE 0 END) AS ready_for_delivery'))
->select(DB::raw('SUM(CASE WHEN order_status_id IN (6) THEN 1 ELSE 0 END) AS out_for_delivery'))
->select(DB::raw('SUM(CASE WHEN order_status_id IN (4, 10, 9, 12, 7) THEN 1 ELSE 0 END) AS completed_order'))
->select(DB::raw('SUM(CASE WHEN order_status_id IN (11, 16, 17, 13) THEN 1 ELSE 0 END) AS waiting_for_cancellation_return_change'))
->get();