sql - 我如何将 SQL 原始查询重写为 Laravel 查询生成器
问题描述
我有完美的 postgresql 查询
select "exhibitions_artworks".*, "curator_rating"."curator_id", "curator_rating"."selected",
"curator_rating"."rating", "curator_rating"."submitted" from "exhibitions_artworks"
full outer join "curator_rating" on "curator_rating"."artwork_id" = "exhibitions_artworks"."id"
where "exhibitions_artworks"."exhibition_id" = 15
and "exhibitions_artworks"."exhibition_id" is not null
and "active" = true
and "exhibitions_artworks"."status" = 0
and "curator_rating"."curator_id" = 71 or "curator_rating"."curator_id" is null
我使用 laravel,我想将其重写为 Laravel 查询生成器。但是 Laravel ORM 不支持full outer join
. 有任何想法吗?
解决方案
在 Laravel 上,如果你想编写原始 SQL,你可以使用DB:raw
.
例子:
$results = DB::select( DB::raw("SELECT * FROM table WHERE column = '$variable'") );
DB::raw()
用于生成查询生成器不会进一步解析的任意 SQL 命令。
(更新)
使用以下 SQL 作为示例:
SELECT * FROM t1 FULL OUTER JOIN t2 ON t1.id = t2.id;
我们也可以使用 UNION 来处理相同的结果:
SELECT * FROM t1 LEFT JOIN t2 ON t1.id = t2.id
UNION ALL
SELECT * FROM t1 RIGHT JOIN t2 ON t1.id = t2.id
在 Laravel 框架中,你可以使用 unionAll 方法:
$first = DB::table('users')
->whereNull('first_name');
$users = DB::table('users')
->whereNull('last_name')
->union($first)
->get();
推荐阅读
- python - 根据当前时间戳获取会计年度-python
- swift - Swift 4 Conform Comparable 协议和排序方法问题
- php - 调用受保护的方法 Symfony\Bundle\FrameworkBundle\Controller\Controller::generateUrl()
- c - 如何在 Linux 上为 GTK+ 设置 C 开发环境?
- unity3d - 使用点光源的阴影
- reactjs - 在 Gatsby 中构建静态 HTML 页面时出错
- rest - 使用 REST API 在 Azure DevOps 中获取所有组织
- java - JAVA获取给定字符串/单词的复数/单数
- reactjs - 如何使用 Bitbucket Pipelines 将 React 项目部署到 ftp?
- download - 如何使用电报 API 下载图像/媒体