Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Laravel's toSql on queries using 'with' clause

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

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?

like image 531
dspitzle Avatar asked Mar 18 '14 18:03

dspitzle


1 Answers

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

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

Troubleshooting

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.

like image 116
The Alpha Avatar answered Nov 07 '22 08:11

The Alpha