Learning Laravel 5.7 on Laracasts.com, it shown how to get 1:N
relationship records from the database with Eloquent model objects as following.
// One SQL query is being executed here.
$project = Project::first();
// Another SQL query must be executed here to be abled to count the tasks. Right?
if ($project->tasks->count()) {
// Is another SQL query being executed here to fetch the task's records related to the project?
foreach ($project->tasks as $task) {
echo $task->name;
}
}
How many SQL query has been executed with the above approach? I am not sure 2 or 3 SQL queries are being executed.
What you are looking for is DB::enableQueryLog/DB::getQueryLog
:
Laravel can optionally log in memory all queries that have been run for the current request. Be aware that in some cases, such as when inserting a large number of rows, this can cause the application to use excess memory. To enable the log, you may use the enableQueryLog
method: DB::connection()->enableQueryLog();
\DB::enableQueryLog();
// One SQL query is being executed here.
$project = Project::first();
// Another SQL query must be executed here to be abled to count the tasks. Right?
if ($project->tasks->count()) {
// Is another SQL query being executed here to fetch the task's records related to the project?
foreach ($project->tasks as $task) {
echo $task->name;
}
}
# queries so far
\DB::getQueryLog();