我有一个由一些条件创建的复杂查询,我想从构建器对象中获取最终的SQL查询即将执行。我能这样做吗?
你可以做到:
$query = DB::table('brands')
->join('products','a','=','c')
->whereNull('whatever');
echo $query->toSql();
但是Laravel不会在查询中显示参数,因为它们在准备查询后被绑定。
所以你也可以这样做:
print_r( $query->getBindings() );
对于调试,这可能非常方便,因为它返回带有绑定的SQL,因此您可以立即将其放入数据库控制台。
/**
* Combines SQL and its bindings
*
* @param \Eloquent $query
* @return string
*/
public static function getEloquentSqlWithBindings($query)
{
return vsprintf(str_replace('?', '%s', $query->toSql()), collect($query->getBindings())->map(function ($binding) {
return is_numeric($binding) ? $binding : "'{$binding}'";
})->toArray());
}
在https://gist.github.com/thonyx/c061d56dc620284ab22526294b43518a找到了这个片段,所以所有学分都来自https://gist.github.com/thonyx :)