在使用“with”子句的查询中使用 Laravel 的 toSql
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22488171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Laravel's toSql on queries using 'with' clause
提问by dspitzle
I'm working in Laravel and I'm interested in checking the SQL statements generated by a Eloquent query that includes a with() statement. For some reason I'm getting only the main query. For example, when I run
我在 Laravel 工作,我有兴趣检查包含 with() 语句的 Eloquent 查询生成的 SQL 语句。出于某种原因,我只得到主要查询。例如,当我运行
class Child extends EloquentVersioned {
public function childRequests()
{
return $this->hasMany('ChildRequest');
}
}
$childQuery = Child::orderBy('last_name')->orderBy('first_name')->with( 'childRequests');
return $childQuery->toSql();
I get back:
我回来了:
select `children`.* from `children` order by `last_name` asc, `first_name` asc
How do I get back the SQL for the with('childRequests') query?
如何取回 with('childRequests') 查询的 SQL?
回答by The Alpha
Actually, when using with
then Laravel
uses another query for that so you are not getting that query output but if you use DB::getQueryLog()
then you'll get all the query logs and to get your log you may run the actual query, for example:
实际上,当使用with
then 时Laravel
使用另一个查询,因此您不会获得该查询输出,但是如果您使用DB::getQueryLog()
then 您将获得所有查询日志并获取您的日志,您可以运行实际查询,例如:
Child::orderBy('last_name')->orderBy('first_name')->with( 'childRequests')->get();
Now try this:
现在试试这个:
dd(DB::getQueryLog()); // an array of all queries
You'll get an output of your queries and you may find the last query using:
您将获得查询的输出,您可能会使用以下命令找到最后一个查询:
$queries = DB::getQueryLog();
dd(end($queries)); // only last query