php - Laravel 查询生成器左连接中的两个表
问题描述
我有以下查询,我正在尝试将其转换为 Laravel 的查询生成器,以便我可以利用自动转义等。
SELECT subjects.name, report_comments.comment
FROM subjects
LEFT JOIN (report_comments, library_comments) ON subjects.id = library_comments.subject_id
AND report_comments.library_comment_id = library_comments.id
AND report_comments.report_id = 1
实际上,查询所说的是“获取所有主题的名称,如果它们有匹配的 report_comment(通过中间library_comments
表),则将其与主题一起返回”(对于给定的标准,主题有一个或零个 report_comments) . 如果我直接在 MySQL 中运行它并返回我期望的结果,则该查询有效。目前report_comment.report_id = 1
是硬编码的,但最终将成为一个占位符,以便report_id
可以传入任何内容。
到目前为止,我已经设法得到:
DB::table('subjects')->select(['subjects.name', 'report_comments.comment'])->leftJoin('report_comments', function ($join) {
$join->on('subjects.id', '=', 'library_comments.subject_id')
->on('report_comments.library_comment_id', '=', 'library_comments.id')
->on('report_comments.report_id', '=', '1');
})
如果我添加toSql
结果是:
select `subjects`.`name`, `report_comments`.`comment` from `subjects` left join `report_comments` on `subjects`.`id` = `library_comments`.`subject_id` and `report_comments`.`library_comment_id` = `library_comments`.`id` and `report_comments`.`report_id` = `1`
这几乎是我想要的,只是它失败了,因为library_comments
根本没有提到该表:
Illuminate/Database/QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'library_comments.subject_id' in 'on clause' (SQL: select `subjects`.`name`, `report_comments`.`comment` from `subjects` left join `report_comments` on `subjects`.`id` = `library_comments`.`subject_id` and `report_comments`.`library_comment_id` = `library_comments`.`id` and `report_comments`.`report_id` = `1`)'
我需要做的是告诉leftJoin
函数report_comments
and library_comments
,但似乎没有任何方法可以做到这一点。我试过:
leftJoin(['report_comments', 'library_comments'], function($join)
猜测 Laravel 可能会将一组表名转换为(report_comments, library_comments)
,但这不起作用并给了我以下警告:
PHP Notice: Array to string conversion in /home/paul/sites/report-assistant/vendor/laravel/framework/src/Illuminate/Database/Grammar.php on line 39
有没有办法将多个表传递到leftJoin
,或者我需要完全重写查询才能使用 Laravel 的查询构建器?
我使用的是laravel/framework
5.8.21 版本,我的所有依赖项都是最新的 ( composer update && npm update
)。
解决方案
采用BD::raw
像这样写查询,它会工作
DB::table('subjects')->select(['subjects.name, report_comments.comment'])->leftJoin(DB::raw('(report_comments, library_comments)'), function ($join) {
$join->on('subjects.id', '=', 'library_comments.subject_id')
->on('report_comments.library_comment_id', '=', 'library_comments.id')
->on('report_comments.report_id', '=', '1');
})
推荐阅读
- vb.net - 自动生成 ID 失败
- cordova - 如何在带有纯 JavaScript 的科尔多瓦中使用离子?
- rest - 如何在 curl 命令中组装抢占式身份验证,同时使用 POST 方法
- ajax - 当我使用 fetch 时,如何修复“加载资源失败:服务器响应状态为 500(内部服务器错误)”
- python - 熊猫数据框之间的点分割忽略其中一个的第一列
- javascript - 未捕获的类型错误:无法读取未定义的属性“refreshContentEditable”
- mysql - GROUP BY 仅具有不同的值相同的字段
- html - 为什么是
高度为 0% 时仍然可见
- c++ - 如何在一个 cmake 文件中集成 g++ 和 gtest
- php - Symfony 传递 post 参数返回相同