stressed out
stressed out

Reputation: 552

Using Laravel's query builder or Eloquent to inner join a table with a temporary one

I have a rather complex query that I'm going to simplify it for making it easier to read:

SELECT `temp_table`.field1, `temp_table`.field2 FROM
(A TEMPORARY TABLE MADE OUT OF A SELECTION QUERY) AS temp_table
INNER JOIN table ON temp_table.field1 = table.id 
WHERE table.some_field = 'something'

I am currently using a RAW query for this, but now I want to rewrite it using either Query Builder or Eloquent ORM in Laravel. I am new to Laravel. So, any idea or help is appreciated.

Upvotes: 2

Views: 1225

Answers (1)

OMR
OMR

Reputation: 12218

try using fromSub

 DB::query()->fromSub(function ($query) {
            $query->selectRaw('your query to get the temp_table');
        }, 'temp_table')->join('table','table.id','=','temp_table.field1')
        ->where('table.some_field','something');

the method 'fromSub' take a string as second parameter, it is 'as' in sql, so you can use it to name the temp table ....

Upvotes: 1

Related Questions