Prasad kv
Prasad kv

Reputation: 103

How to select data from a sub query using laravel query builder

The code below is not working.

$subQuery = DB::table('table1')->groupBy('col');

$data = DB::table($subQuery, 'sub')->get();

Can you help me with this?

Upvotes: 0

Views: 610

Answers (1)

IGP
IGP

Reputation: 15849

Your code is already functional. The only alternative (to make the same query) is to inline the $subQuery part.

$subQuery = DB::table('table1')->groupBy('col');

$data = DB::table($subQuery, 'sub')->get();

Is the same as

$data = DB::table(function ($sub) {
        $sub->from('table1')
            ->groupBy('col');
    }, 'sub')
    ->get();

or

$data = DB::table(DB::table('table1')->groupBy('col'), 'sub')->get();

Upvotes: 5

Related Questions