【问题标题】:How many times does Laravel 5.7 execute the SQL query?Laravel 5.7 执行 SQL 查询多少次?
【发布时间】:2019-06-19 11:31:51
【问题描述】:

在 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 查询。

【问题讨论】:

  • 这里运行了两个查询。加载项目的第一个查询,然后将 $project->tasks 加载到集合中的第二个查询。然后count() 和 foreach 都在加载的集合上运行,但不需要更多的数据库查询。
  • 因此,由于 $project->tasks 就在 ->count() 执行 SELECT * FROM ... 查询并在 count() 被调用后立即对它们进行计数,而不是执行SELECT COUNT(*) FROM ... 查询。

标签: php sql laravel-5


【解决方案1】:

你要找的是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();

【讨论】:

  • 它不回答问题,但给了我一个新的知识来得到答案,从而间接回答。我为你投了 1 票作为有用的答案!
猜你喜欢
  • 1970-01-01
  • 2014-01-28
  • 2019-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多