laravel db query

时间:2018-01-29 03:55:11

标签: laravel laravel-5.4

我需要在使用连接时获得 ProductQTY groupBy ProductID 的总和,使用db::raw时总是会出错,这里附带的是我的代码< / p>

$pick_list_items = DB::table('pick_list_detail')
                   ->where('pick_list_detail.pick_list_id',$id)
                   ->join('sale_invoices', 'pick_list_detail.sale_invoice_id','=','sale_invoices.id')
                   ->join('sale_invoice_detail', 'sale_invoice_detail.sale_invoice_id','=','pick_list_detail.sale_invoice_id')
                   ->select(['pick_list_detail.sale_invoice_id', 'sale_invoice_detail.product_id', 'sale_invoice_detail.product_qty', 'sale_invoice_detail.uom', 'sale_invoice_detail.uom_factor'])
                   ->sum('sale_invoice_detail.product_qty')
                   ->groupBy('sale_invoice_detail.product_id')
                   ->get();

我正在使用laravel 5.4

这是错误

  

(2/2)QueryException       SQLSTATE [42000]:语法错误或访问冲突:1055'fdis.pick_list_detail.sale_invoice_id'不在GROUP BY中(SQL:select   pick_list_detailsale_invoice_id,   sale_invoice_detailproduct_id,   sale_invoice_detailproduct_qtysale_invoice_detailuom,   来自sale_invoice_detail内部联接的uom_factorpick_list_detail   sale_invoices上的pick_list_detailsale_invoice_id =   sale_invoicesid内部加入sale_invoice_detail   sale_invoice_detailsale_invoice_id =   pick_list_detailsale_invoice_id其中   pick_list_detailpick_list_id = 1分组依据   sale_invoice_detailproduct_id

enter image description here

1 个答案:

答案 0 :(得分:0)

    $sale_invoices = DB::table('pick_list_detail')
    ->select(DB::raw('sum(sale_invoice_detail.product_qty) as si_count, pick_list_detail.pick_list_id , sale_invoice_detail.product_id , sale_invoice_detail.uom, sale_invoice_detail.uom_factor '))
    ->where('pick_list_detail.pick_list_id',$id)
    ->join('sale_invoices', 'pick_list_detail.sale_invoice_id','=','sale_invoices.id')
    ->join('sale_invoice_detail', 'sale_invoice_detail.sale_invoice_id','=','pick_list_detail.sale_invoice_id')
    ->groupBy('pick_list_detail.pick_list_id')
    ->groupBy('sale_invoice_detail.product_id')
    ->groupBy('sale_invoice_detail.uom')
    ->groupBy('sale_invoice_detail.uom_factor')
    ->get();

原始查询是我的解决方案。