在Laracasts.com上学习Laravel 5.7,它显示了如何使用Eloquent模型对象从数据库中获取1:N
关系记录。
// 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;
}
}
使用上述方法已执行了多少SQL查询?我不确定要执行2或3个SQL查询。
答案 0 :(得分:0)
您要寻找的是DB::enableQueryLog / DB::getQueryLog
:
Laravel可以选择将所有已运行的查询登录到内存中 对于当前请求。请注意,在某些情况下,例如何时 插入大量的行,这可能导致应用程序 使用多余的内存。要启用日志,您可以使用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();