【发布时间】: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 ... 查询。