laravel Eloquent ORM - How to get compiled query?

3.2k Views Asked by At

In Laravel 4.2 I want to get Compiled Query.

This is what i have:

$product = Product::where('id', '=', '100')->get();

I want compiled query like:

select * from products where id = 100 

Purpose of the question is: i want to use it as sub query in another query.

I have searched and found Class Grammer and Class MySQL But i did not found solution for that.

Is there any solution?

Your help would be appreciated.

4

There are 4 best solutions below

0
On BEST ANSWER

You can use grammer for subqueries, See below example for reference :

$users = DB::table('users')
             ->where('user.id', '=', $userID)
             ->join('product', 'product.userid',  '=', 'user.id');

$price = $users->select(array(DB::raw('SUM(price)')))
               ->grammar
               ->select($users); // Compiles the statement

$result = DB::table('users')->select(array(DB::raw("({$price}) as price)))->get();

This add a subquery to your main query.

2
On

The easiest way is probably mostly finding out what query was just executed, rather than what the query will be. Something like this:

function latestQuery()
{
    $queries = DB::getQueryLog();
    return end($queries);
}

Hopefully that's the same for your purposes.

2
On

You can register an event listener in your routes file(in development phase), which will listen for the laravel query event and var_dump the executed query.

Event::listen('illuminate.query', function($sql)
{
    var_dump($sql);
});

But this will turn out to be messy. So better use something like Clockwork. It is awesome, you can view all the executed query in your browser.

0
On

You can get the SQL query like this:

use DB;//write this at the top of the file above your Class 

DB::enableQueryLog();//Enable query logging
$product = Product::where('id', '=', '100')->get();
dd(DB::getQueryLog());//print the SQl query