Limon Monte
Limon Monte

Reputation: 54459

Laravel - named subquery using Query Builder

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

Upvotes: 2

Views: 302

Answers (1)

Bogdan
Bogdan

Reputation: 44586

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.*');

Upvotes: 2

Related Questions