我在 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 useDB::enableQueryLog()
before.
关于laravel - 在使用 'with' 子句的查询中使用 Laravel 的 toSql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22488171/