2

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

Limon Monte
  • 52,539
  • 45
  • 182
  • 213

1 Answers1

2

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.*');
Bogdan
  • 43,166
  • 12
  • 128
  • 129
  • You may add brackets to avoid an SQL syntax error `'('.$subquery->toSql().') as subquery_name'` – Koeffi May 31 '18 at 12:29