Laravel查询生成器常规错误2031

时间:2016-08-03 00:38:43

标签: php mysql laravel query-builder

以下是使用Laravel查询构建器的查询:

<select data-select-size-key="0" id="popular_sizes_0" name="popular_sizes_0">
<option></option>
</select>

我希望得到如下结果:

$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();

但后来我一直在 SQLSTATE [HY000]:一般错误:2031 。所以我在查询中使用了 toSql()来获取原始的sql查询并试图在MySQL中运行它并且它产生了如上所述的预期结果。

以下是运行toSql()

后的查询
"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"
            }
        ]

所以问题是,我的查询构建器出了什么问题?为什么原始sql在查询构建器不工作时有效?

由于

1 个答案:

答案 0 :(得分:9)

经过大量研究,似乎我错过了这个

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();