问题
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
Is there any way to do this in Laravel Query Builder without using DB::raw()
?
回答1:
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.*');
来源:https://stackoverflow.com/questions/29970481/laravel-named-subquery-using-query-builder