在使用'with'子句的查询中使用Laravel的toSql [英] Using Laravel's toSql on queries using 'with' clause

查看:675
本文介绍了在使用'with'子句的查询中使用Laravel的toSql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Laravel工作,我感兴趣的是检查Eloquent查询(包括with()语句)生成的SQL语句.由于某种原因,我只得到主要查询.例如,当我跑步

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

class Child extends EloquentVersioned {
    public function childRequests()
    {
        return $this->hasMany('ChildRequest');
    }   

}
$childQuery = Child::orderBy('last_name')->orderBy('first_name')->with( 'childRequests');
return $childQuery->toSql();

我回来了:

select `children`.* from `children` order by `last_name` asc, `first_name` asc

如何获取with('childRequests')查询的SQL?

How do I get back the SQL for the with('childRequests') query?

推荐答案

实际上,当使用with时,Laravel使用另一个查询,因此您不会获得该查询输出,但是如果使用DB::getQueryLog(),则您'将获取所有查询日志,并获取您的日志,您可以运行实际的查询,例如:

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:

Child::orderBy('last_name')->orderBy('first_name')->with( 'childRequests')->get();

现在尝试:

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

这篇关于在使用'with'子句的查询中使用Laravel的toSql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆