将SQL查询SELECT SUM转换为laravel 5

时间:2016-09-28 06:53:59

标签: php mysql laravel laravel-5

我有这个SQL查询

select sum(repayment_borrower.settle_amount+ repayment_borrower.settle_interest + repayment_borrower.settle_penalty) as Total Default
     FROM repayment_borrower,loans,loan_offer, lender
     WHERE repayment_borrower.loans_id = loans.id
     AND loan_offer.loan_id = loans.id
     AND loans.lnsts <> 999
     AND loans.lnsts = 810
     AND loan_offer.lender_id = lender.id
     and lender.user_id = "3" 

当我在sql phpmyadmin中应用时,此代码有效。但是,当我像laravel这样转换时

$count_badloans        =  DB::select( DB::raw("SELECT sum(repayment_borrower.settle_amount+ repayment_borrower.settle_interest + repayment_borrower.settle_penalty) as Total Default
                                                    FROM repayment_borrower,loans,loan_offer, lender
                                                    WHERE repayment_borrower.loans_id = loans.id
                                                    AND loan_offer.loan_id = loans.id
                                                    AND loans.lnsts <> 999
                                                    AND loans.lnsts = 810
                                                    AND loan_offer.lender_id = lender.id
                                                    and lender.user_id = $userId ") );

发生了这样的错误

error

我将查询应用于laravel是错误的吗?请帮忙.....

提前感谢。

2 个答案:

答案 0 :(得分:1)

尝试这样做,将Total Default Set设为Total_Default(不含空格)或简单Total

$count_badloans  =  DB::select("SELECT sum(repayment_borrower.settle_amount+ repayment_borrower.settle_interest + repayment_borrower.settle_penalty) as Total 
                                                FROM repayment_borrower,loans,loan_offer, lender
                                                WHERE repayment_borrower.loans_id = loans.id
                                                AND loan_offer.loan_id = loans.id
                                                AND loans.lnsts <> 999
                                                AND loans.lnsts = 810
                                                AND loan_offer.lender_id = lender.id
                                                and lender.user_id = $userId ");

答案 1 :(得分:0)

@arbong你能删除别名Total Default吗?

$count_badloans        =  DB::select(DB::raw("SELECT
  SUM(repayment_borrower.settle_amount + repayment_borrower.settle_interest + repayment_borrower.settle_penalty)
FROM repayment_borrower,
     loans,
     loan_offer,
     lender
WHERE repayment_borrower.loans_id = loans.id
AND loan_offer.loan_id = loans.id
AND loans.lnsts <> 999
AND loans.lnsts = 810
AND loan_offer.lender_id = lender.id
AND lender.user_id = $userId "));