Laravel 查询生成器一般错误 2031
Posted
技术标签:
【中文标题】Laravel 查询生成器一般错误 2031【英文标题】:Laravel query builder General error 2031 【发布时间】:2016-12-08 12:36:42 【问题描述】:以下是我使用 Laravel 查询生成器的查询:
$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 可以工作,而查询生成器却不行?
谢谢
【问题讨论】:
为什么不把不涉及raw的原代码贴出来呢 @e4c5 已经更新了 我有点困惑,很明显你的 laravel 代码使用的是 raw,但你说 raw 查询有效。那么它不起作用是什么?? @e4c5 Laravel 代码给了我错误,而下面的原始 sql 正在返回我的结果。我知道 laravel 代码与原始 sql 完全一样,这就是为什么我不知道为什么它不能正常工作 【参考方案1】:经过大量研究,我似乎错过了这个
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();
【讨论】:
谢谢!感谢您的研究,节省了我的时间!就我而言,我有一个带有自己绑定的子查询。以上是关于Laravel 查询生成器一般错误 2031的主要内容,如果未能解决你的问题,请参考以下文章