2

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.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
akash varlani
  • 320
  • 1
  • 4
  • 16

4 Answers4

4

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.

Joel Hinz
  • 24,719
  • 6
  • 62
  • 75
3

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
Rahul Gupta
  • 9,775
  • 7
  • 56
  • 69
1

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.

Shhetri
  • 152
  • 7
-3

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.

Arjun
  • 1,431
  • 1
  • 12
  • 32