来自普通查询的laravel查询构建器

时间:2015-06-19 10:14:16

标签: laravel-4

DB::select(DB::raw( 'SELECT a.bill_no, a.account_id, a.bill_date, a.amount_paid,
                                b.transaction_code,b.amount from  bill_det a left join
                                (select bill_no, transaction_code, sum(amount) as amount from payment_transactions 
                                where status = "success" group by bill_no ) b
                                on a.bill_no = b.bill_no where a.amount_paid != b.amount order by b.bill_no'));

这是正常的查询。更改为laravel查询? 我试过了。

$bill=DB::table('bill_det')->leftJoin('payment_transactions', 'bill_det.bill_no', '=', 'payment_transactions.bill_no')
                                ->select('bill_det.bill_no','bill_det.account_id','bill_det.bill_date','bill_det.amount_paid',
                                'payment_transactions.transaction_code',DB::raw('sum(payment_transactions.amount) as amount'))
                                ->where('payment_transactions.status','=','success')
                                ->where('sum(payment_transactions.amount)','!=',DB::raw('bill_det.amount_paid'))
                                ->groupBy('bill_det.bill_no')
                                ->orderBy('bill_det.bill_no','desc');

我无法比较-> where('sum(payment_transactions.amount)','!=',DB::raw('bill_det.amount_paid'))

我像这样使用->whereRaw('bill_det.amount_paid != sum(payment_transactions.amount)')

  

{"错误" {"类型":"照亮\数据库\ QueryException""消息":" SQLSTATE [HY000]:常规错误:1111无效使用组功能(SQL:选择计数(*)作为聚合来自(选择' 1' as row_count from bill_det left join payment_transactions on bill_detbill_no = payment_transactionsbill_no其中payment_transactionsstatus =成功和bill_det.amount_paid!= sum(payment_transactions.amount)组按bill_detbill_nobill_det排序。bill_no desc)count_row_table)"

1 个答案:

答案 0 :(得分:0)

DB::select(DB::raw( 'SELECT a.bill_no, a.account_id, a.bill_date, a.amount_paid,
                            b.transaction_code,b.amount from  bill_det a left join
                            (select bill_no, transaction_code, sum(amount) as amount from payment_transactions 
                            where status = "success" group by bill_no ) b
                            on a.bill_no = b.bill_no where a.amount_paid != b.amount order by b.bill_no'));

将此转换为laravel Query ::

$query = \Illuminate\Support\Facades\DB::table('bill_det')
            ->select('a.bill_no', 'a.account_id', 'a.bill_date', 'a.amount_paid', 'b.transaction_code', 'b.amount')
            ->leftJoin(DB::raw('(select bill_no, transaction_code, sum(amount) as amount from payment_transactions 
                            where status = "success" group by bill_no) b'), function($join) {
                $join->on('a.bill_no', '=', 'b.bill_no');
            })
            ->where('a.amount_paid','<>', 'b.amount')
             ->orderBy('b.bill_no')
            ->get();

如果你想知道如何在里面使用原始表达式,那么使用它:

$query->whereRaw(DB::raw('(your expression!!)'));