给定以下代码:

DB::table('users')->get();

我想得到上面的数据库查询生成器将生成的原始SQL查询字符串。在本例中,它将是SELECT*FROM用户。

我该怎么做?


当前回答

第一个选项

当然,有一些方法可以只输出一个查询,并在phpMyAdmin或其他工具中对其进行调试,以了解查询的执行方式。

一种将查询与变量(也称为绑定)一起转储的好方法,您可以将以下函数添加为项目中的公共助手

function queryToSQL($query, $logQuery = true)
{
    $addSlashes = str_replace('?', "'?'", $query->toSql());

    $sql = str_replace('%', '#', $addSlashes);

    $sql = str_replace('?', '%s', $sql);

    $sql = vsprintf($sql, $query->getBindings());

    $sql = str_replace('#', '%', $sql);

    if ($logQuery) {
        Log::debug($sql);
    }

    return $sql;
}

第二个选项

这是另一种方法,而不是转储每个查询,您可以使用Telescope,该工具可以让您更深入地了解可能在后台启动的所有查询,以及每个查询花费的时间以及显示的所有绑定

第三种选择

Laravel Debugbar是一个非常棒的插件,它可以帮助您在小的底部栏下调试所有内容,但这仅适用于基于UI的活动,对于API或命令,调试方式被忽略了,Telescope成为了一个很好的助手

其他回答

最简单的方法是故意犯错误。例如,我想查看以下关系的完整SQL查询:

public function jobs()
{
    return $this->belongsToMany(Job::class, 'eqtype_jobs')
        ->withPivot(['created_at','updated_at','id'])
        ->orderBy('pivot_created_at','desc');
}

我只是想创建一个找不到的列,这里我选择了created_at,并通过添加尾随s将其更改为created_ats:

public function jobs()
{
    return $this->belongsToMany(Job::class, 'eqtype_jobs')
        ->withPivot(['created_ats','updated_at','id'])
        ->orderBy('pivot_created_at','desc');
}

因此,调试器将返回以下错误:

(4/4)ErrorException SQLSTATE[42S22]:未找到列:1054未知“字段列表”中的列“eqtype_jobs.created_ats”(SQL:selectjobs.*,eqtype_jobs.set_id作为pivot_set_id,eqtype_jobs.job_id作为pivot_job_id,eqtype_jobs.created_ats作为pivot_created_ats,eqtype_jobs.updated_at作为pivot_updated_at,eqtype_jobs.id作为内部作业的pivot_id在jobs.id上加入eqtype_jobs.job_id,其中eqtype_jobs.set_id=56在desc limit 20时按pivot_created排序偏移量0)(视图:/home/ssad/www/factory/resources/views/set/show.blade.php)

上面的错误消息返回带有错误的完整SQL查询

SQL: select  jobs.*, eqtype_jobs.set_id as pivot_set_id,  eqtype_jobs.job_id as pivot_job_id, eqtype_jobs.created_ats as pivot_created_ats, eqtype_jobs.updated_at as  pivot_updated_at, eqtype_jobs.id as pivot_id from jobs inner join eqtype_jobs on jobs.id = eqtype_jobs.job_id where  eqtype_jobs.set_id = 56 order by pivot_created_at desc limit 20 offset 0

现在,只需从created_at中删除多余的s,并在任何SQL编辑器(如phpMyAdmin SQL编辑器)中测试该SQL!

###通知:该溶液已经用Laravel 5.4进行了测试。

将此函数添加到应用程序中,只需调用。

function getQuery($sql){
        $query = str_replace(array('?'), array('\'%s\''), $sql->toSql());
        $query = vsprintf($query, $sql->getBindings());     
        return $query;
}

输出:“根据updated_at desc limit 25 offset 0从用户中选择*,其中lang='en',status='1'”

有一种获取查询字符串的方法。

到SQL()

在我们的情况下,

 DB::table('users')->toSql(); 

回来

select * from users

是返回SQL查询字符串的确切解决方案。。希望这有帮助。。。

打印上次查询

DB::enableQueryLog();

$query        = DB::getQueryLog();
$lastQuery    = end($query);
print_r($lastQuery);

为了记录所有执行的查询,可以使用DB::enableQueryLog()icw DB::getQueryLog(()。输出具有以下结构。

[
  [
    "query" => "select * from "users" where name = ?"
    "bindings" => ["John Doe"]
    "time" => 0.34
  ],
  ...
]

此外,我在这里结合了一些答案,以便获得完美的函数,用编译的绑定解析sql。见下文。我甚至创建了一个实现此功能的自定义生成器类,例如User::where('name','JohnDoe')->parse();

function parse_sql(string $sql, array $bindings) : string
{
  $compiled_bindings  = array_map('compile_binding', $bindings);

  return preg_replace_array("/\?/", $compiled_bindings, $sql);
}

function compile_binding($binding)
{
  $grammar = new MySqlGrammar;

  if (is_bool($binding))
  {
    return (int)$binding; //This line depends on the database implementation
  }

  if(is_string($binding))
  {
    return "'$binding'";
  }

  if ($binding instanceof DateTimeInterface)
  {
    return $binding->format($grammar->getDateFormat());
  }

  return $binding;
}