我有以下原始查询,是否可以使用Laravel Query Builder或Eloquent创建此查询?
SELECT
SUM(records.per_hub)+SUM(records.additionl_qty) AS qty,
records.cost_price,
(records.cost_price)*(SUM(records.per_hub)+SUM(records.additionl_qty)) AS
total
FROM
(SELECT
COUNT(*) AS per_hub,
CEIL(COUNT(*) * 50 / 100) AS additionl_qty,
m.cost_price
FROM
orders o
LEFT JOIN meals m
ON m.id = o.meal_id
WHERE o.shift_id = 1
AND o.meal_id = 2
AND o.city_id = 283
AND o.restaurant_id = 5
GROUP BY hub_id) records;
答案 0 :(得分:1)
以它为参考。
$sub_query = DB::table('orders as o')
->leftJoin('meals as m','m.id','=','o.meal_id')
->where('o.shift_id','=',1)
->where('o.meal_id','=',2)
->where('o.city_id','=',283)
->where('o.restaurant_id', '=', 5)
->select(DB::raw('COUNT(*) AS per_hub,CEIL(COUNT(*) * 50 / 100) AS additionl_qty,m.cost_price'))
->groupBy('hub_id');
$main_query = DB::table( DB::raw("({$sub_query->toSql()}) as records") )
->select(DB::raw('SUM(records.per_hub)+SUM(records.additionl_qty) AS qty,
records.cost_price,
(records.cost_price)*(SUM(records.per_hub)+SUM(records.additionl_qty)) AS total'))
->get();
答案 1 :(得分:0)
是的,可以使用Laravel Query Builder创建它,尝试查找API文档:https://laravel.com/api/5.6/Illuminate/Database/Query/Builder.html#method_addSelect