php - Laravel 查询生成器左连接中的两个表

标签 php mysql 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 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');
})

关于php - Laravel 查询生成器左连接中的两个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56495238/

相关文章:

mysql - 按照另一个表中另外两列的计数总和的顺序获取表行

php - 在 Laravel 5.1 中手动创建分页器

php - 有哪些更有效的方法来处理查询?

javascript - 在带有 codeigniter 的 PHP 5.4 中使用 session 上传进度条

mysql 哪里不在左外连接中

mysql - Mysql中如何删除重复行,条件是另一列为空

mysql - 无法更改表以添加外键?

php - Laravel 阻止特定路由的数据库访问

php - 如何将 WAMP + PHP Orange 样式错误报告更改为普通文本格式

php - 在 MYSQL 中存储 URL 值