2016-08-03 71 views
4

下面是一個使用我的查詢Laravel查詢生成器:Laravel查詢生成器一般錯誤2031

$begin = new DateTime('2016-07-01'); 
$end = new DateTime('2016-07-31'); 
$startDate = $begin->format('Y-m-d 00:00:00'); 
$endDate = $end->format('Y-m-d 23:59:59'); 
$deposit = $depositModel->select(DB::raw('user_deposit.user_id as user_id, sum(user_deposit.amount) as total_deposit, null as total_withdraw')) 
         ->whereBetween('date_time', [$startDate, $endDate]) 
         ->where('user_deposit.status', 1) 
         ->groupBy('user_deposit.user_id'); 
$withdraw = $withdrawModel->select(DB::raw('user_withdraw.user_id as user_id, null as total_deposit, sum(user_withdraw.amount) as total_withdraw')) 
         ->whereBetween('user_withdraw.created_at', [$startDate, $endDate]) 
         ->where('user_withdraw.status', 1) 
         ->groupBy('user_withdraw.user_id'); 
$deposit = $deposit->unionAll($withdraw); 
$transaction = DB::table(DB::raw("({$deposit->toSql()}) t")) 
        ->select('user_id', DB::raw("sum(total_deposit) as total_deposit_amount, sum(total_withdraw) as total_withdraw_amount")) 
        ->groupBy('user_id') 
        ->get(); 

我希望得到的結果如下圖所示:

"transaction": [ 
      { 
       "user_id": 2, 
       "total_deposit_amount": "101.00", 
       "total_withdraw_amount": "50.50" 
      }, 
      { 
       "user_id": 5, 
       "total_deposit_amount": null, 
       "total_withdraw_amount": "50.50" 
      } 
     ] 

但後來我不斷收到SQLSTATE [ HY000]:一般錯誤:2031。所以我使用toSql()查詢來獲得原始的sql查詢,並試圖在MySQL中運行它,併產生了如上所示的預期結果。

下面是運行後查詢toSql()

SELECT`user_id`, SUM(total_deposit) AS total_deposit_amount, SUM(total_withdraw) AS total_withdraw_amount 
FROM ((SELECT user_deposit.user_id AS user_id, SUM(user_deposit.amount) AS total_deposit, null AS total_withdraw 
     FROM `user_deposit` 
     WHERE`date_time` BETWEEN '2016-07-01' AND '2016-07-31' 
     AND `user_deposit`.`status` = 1 
     GROUP BY `user_deposit`.`user_id`) 
     UNION ALL (SELECT user_withdraw.user_id AS user_id, null AS total_deposit, SUM(user_withdraw.amount) AS total_withdraw 
        FROM `user_withdraw` 
        WHERE `user_withdraw`.`created_at` BETWEEN '2016-07-01' AND '2016-07-31' 
        AND `user_withdraw`.`status` = 1 
        GROUP BY `user_withdraw`.`user_id`)) t 
     GROUP BY `user_id` 

所以,問題是,這有什麼錯我的查詢生成器?爲什麼在查詢生成器不工作的情況下,原始sql工作?

感謝

+0

爲什麼不公佈原始代碼的一個沒有不涉及原始的 – e4c5

+0

@ e4c5已經更新了 –

+0

我有點困惑清楚你的laravel代碼使用原始的,但你說原始查詢的作品。那麼它是什麼不行? – e4c5

回答

7

經過反覆研究,好像我已經錯過了這個

mergeBindings($sub->getQuery()) 

我的代碼:

$transaction = DB::table(DB::raw("({$deposit->toSql()}) t")) 
        ->mergeBindings($sub->getQuery()) // this is required for selecting from subqueries 
        ->select('user_id', DB::raw("sum(total_deposit) as total_deposit_amount, sum(total_withdraw) as total_withdraw_amount")) 
        ->groupBy('user_id') 
        ->get();