NewbieCoder
NewbieCoder

Reputation: 706

How do I select an alias table for my laravel eloquent DB::table?

Say, I want to have an alias table as my DB::table

(
    SELECT A, B, C 
    FROM TABLE
    WHERE D = 'xx'
) custom_table

How is it possible to convert this into Eloquent's DB::table?

I tried,

DB::table(
    DB::select(
        DB::raw(
            SELECT * FROM (SELECT A, B, C FROM TABLE WHERE D = :param1) AS custom_table
        ),
        [ "param1" => "xx" ]
    )
)

But this seems to give me

ErrorException: Array to string conversion

Upvotes: 0

Views: 1608

Answers (1)

Ronak Dhoot
Ronak Dhoot

Reputation: 2321

Treat that as 2 different query builders and merge their binding like below :

$xx = 'xx';
$innerQuery = DB::select('A','B','C')->table('TABLE')->where('D', '=',$xx);

$mainQuery = DB::table(DB::raw('(' . $innerQuery->toSql() . ') as custom_table'))
    ->mergeBindings($innerQuery)
    ->groupBy('custom_table.C')
    ->get();

This will also help you retail the $innerQuery builder instance for your later use as you have mentioned in the question.

Upvotes: 1

Related Questions