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.

4

4 回答 4

4

最简单的方法可能主要是找出刚刚执行的查询,而不是查询将是什么。像这样的东西:

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

希望这对于您的目的是相同的。

于 2014-12-10T05:49:27.933 回答
3

您可以像这样获取 SQL 查询:

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
于 2017-06-15T05:03:34.753 回答
1

你可以在你的路由文件中注册一个事件监听器(在开发阶段),它将监听 laravel 查询事件和var_dump执行的查询。

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

但这将变得一团糟。所以最好使用像Clockwork这样的东西。太棒了,您可以在浏览器中查看所有已执行的查询。

于 2014-12-10T06:02:23.420 回答
-2

您可以使用grammerfor subqueries,请参阅以下示例以供参考:

$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();

这会向您的主查询添加一个子查询。

于 2014-12-10T06:34:29.757 回答