如何将sql原始查询重写为laravel查询生成器

3df52oht  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(285)

我有一个完美的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 . 有什么想法吗?

5lhxktic

5lhxktic1#

在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;

我们也可以使用并集来处理相同的结果:

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

参考文献:https://laravel.com/docs/7.x/queries#unions

相关问题