laravel - 在使用 'with' 子句的查询中使用 Laravel 的 toSql

标签 laravel eloquent

我在 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();

我回来了:
select `children`.* from `children` order by `last_name` asc, `first_name` asc

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

最佳答案

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

Child::orderBy('last_name')->orderBy('first_name')->with( 'childRequests')->get();
现在试试这个:
dd(DB::getQueryLog()); // an array of all queries
您将获得查询的输出,您可能会使用以下命令找到最后一个查询:
$queries = DB::getQueryLog();
dd(end($queries)); // only last query
故障排除

If you get no results on DB::getQueryLog() then the Query Logger may be disabled at all and you have to use DB::enableQueryLog() before.

关于laravel - 在使用 'with' 子句的查询中使用 Laravel 的 toSql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22488171/

相关文章:

php - Laravel 模型函数获取相关实体描述为字符串

Laravel JSON API : How to create custom virtual resource from database (for aggregated values)?

php - Laravel Eloquent 关系 - 不根据条件获取

php - get() 不起作用,但 First() 起作用。我需要使用 get() 来获取我的所有数据

laravel - 如何使用 Laravel 的 Eloquent/Fluent 将每一行设置为相同的值?

php - 拉维尔 4.2 : How to use order by SUM in Laravel

php - 更改apache2 php路径

backbone.js - 拉拉维尔。如何在 Backbone 中获取/传递登录用户 ID

laravel - 如何更新 laravel/homestead?

php - Laravel:目标 [Lcobucci\JWT\Parser] 不可实例化