将SQL查询转储到Laravel中的屏幕
问题描述:
我正在尝试将实际的SQL查询输出到屏幕。我添加了以下路由:
I'm trying to output the actual SQL queries to the screen. I've added the following route:
// Display all SQL executed in Eloquent
Event::listen('illuminate.query', function($query)
{
var_dump($query);
});
这主要是工作,但有些值出现问号:
This works mostly, but some values come out as question marks:
select DATE_FORMAT(DATE(`created_at`),'%b %d') as `date`, created_at, COUNT(*) as `count`
from `contacts`
where `created_at` > ? and `list_name` = ? or `list_name` = ? or `list_name` = ?
group by `date`
order by `created_at` asc
是否一个获得完整查询的方法来输出我动态添加的实际值,而不是无益的'?'字符?
Is there a way to get the full query to output the actual values I'm dynamically adding, rather than unhelpful '?' characters?
答
是的,您可以使用以下代码:
Yes, you can use this code:
Event::listen(
'illuminate.query',
function ($sql, $bindings, $time) {
$sql = str_replace(array('%', '?'), array('%%', "'%s'"), $sql);
$full_sql = vsprintf($sql, $bindings);
file_put_contents(storage_path() . DIRECTORY_SEPARATOR . 'logs'
. DIRECTORY_SEPARATOR . 'sql_log.sql', $full_sql . ";\n",
FILE_APPEND);
}
);
我在本地环境中将输出保存到文件中,当然可以在屏幕上显示此查询。
In mine I save output to file in local environment, you can of course display this query on screen.