Laravel - 使用查询生成器命名子查询

2022-01-23 00:00:00 subquery php mysql laravel query-builder

在 MySQL 子查询 文档中有一个子查询示例:

In MySQL subqueries documentation there's an exmaple of subquery:

SELECT ... FROM (subquery) [AS] name ...

这是我要转换的原始查询:

Here's the raw query which I want to transform:

select SUBQUERY_NAME.* from (select id, name from items) AS SUBQUERY_NAME

在 Laravel Query Builder 中有什么方法可以在不使用 DB::raw() 的情况下做到这一点?

Is there any way to do this in Laravel Query Builder without using DB::raw()?

推荐答案

不幸的是没有.查询构建器有其局限性,更复杂的查询超出了它的范围,这就是 DB::raw() 存在的原因.但是,如果你想让它更优雅一点并使用查询生成器生成子查询,你可以这样做:

Unfortunatelly no. The Query Builder has its limitations and more complex queries are outside its scope, that's why DB::raw() is there. But, if you want to make it a little more elegant and generate the subquery using the Query Builder, you could do something like this this:

$subquery = DB::table('items')->select('id', 'name')->toSql();
DB::table(DB::raw($subquery . ' as subquery_name'))->select('subquery_name.*');

相关文章