如何将这个MySQL查询写入Laravel的Eloquent?
SELECT
products.pro_code AS code,
products.name AS product,
sum(ppurchases.quantity) AS total_quantity,
products.reorder_point AS reorder_point,
products.selling_price AS selling_price,
min(ppurchases.expiry_date) AS nearest_expiry
FROM `ppurchases`
JOIN `products`
WHERE ppurchases.product_id = products.id
GROUP BY products.name
我写的如下,但无法成功。
$products = DB::table('products')
->JOIN('ppurchases','ppurchases.product_id', '=','products.id')
->select('products.pro_code as code','products.name as product','products.reorder_point as reorder_point','products.selling_price as selling_price',DB::raw('min(ppurchases.expiry_date) as nearest_expiry'))
->where('ppurchases.product_id','products.id')
->groupBy('products.name')
->get();
答案 0 :(得分:1)
在使用Raw
时使用每个前缀$products = DB::table('products')
->join('ppurchases', 'ppurchases.product_id', '=', 'products.id')
->select(
'products.name as product',
DB::raw('min(per_ppurchases.expiry_date) as nearest_expiry')
)
->groupBy('products.name')
->get();
答案 1 :(得分:0)
编辑:更新到新表名。
由于默认的Homestead sql_mode = only_full_group_by标志,我收到了非聚合列错误。添加2加法MAX(你可以用MIN()代替,或AVG()似乎可以解决问题。
$result = DB::table('per_ppurchases')
->join('per_products', 'per_ppurchases.product_id', '=', 'per_products.id')
->select(
'per_products.name as code',
'per_products.name as product',
DB::raw('SUM(per_ppurchases.quantity) as total_quantity'),
DB::raw('MAX(per_products.reorder_point) as reorder_point'),
DB::raw('MAX(per_products.selling_price) as selling_price'),
DB::raw('MIN(per_ppurchases.expiry_date) as nearest_expiry')
)
->groupBy('per_products.name')
->get();