我真的对laravel关系感到惊讶,因为它给出的结果没有重复的条目,而如果与左连接比较的话。例如,最近我尝试了self-join,将多个连接到同一个表
public function parentMenu(){
return $this->hasMany(Page::class,'parent_page_id','id');
}
并返回以下结果
Array
(
[0] => Array
(
[id] => 1
[page_name] => Branch Details
[page_url] => #
[parent_page_id] => 0
[page_type] => 1
[created_at] => 2018-06-23 23:45:34
[updated_at] => 2018-06-23 23:45:34
[deleted_at] =>
[slug] => branch_detail
[parent_menu] => Array
(
[0] => Array
(
[id] => 2
[page_name] => Add Branch Detail
[page_url] => add-branch
[parent_page_id] => 1
[page_type] => 1
[created_at] => 2018-06-23 23:45:54
[updated_at] => 2018-06-23 23:45:54
[deleted_at] =>
[slug] => add_branch_detail
)
[1] => Array
(
[id] => 11
[page_name] => View Branch Detail
[page_url] => list-branch
[parent_page_id] => 1
[page_type] => 1
[created_at] => 2018-06-23 23:46:08
[updated_at] => 2018-06-23 23:46:08
[deleted_at] =>
[slug] =>
)
)
)
我也试着找出问题所在
Array
(
[0] => Array
(
[query] => select * from `pages` where `pages`.`deleted_at` is null
[bindings] => Array
(
)
[time] => 0.82
)
[1] => Array
(
[query] => select * from `pages` where `pages`.`parent_page_id` in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) and `pages`.`deleted_at` is null
[bindings] => Array
(
[0] => 1
[1] => 2
[2] => 4
[3] => 5
[4] => 7
[5] => 8
[6] => 9
[7] => 10
[8] => 11
[9] => 12
)
[time] => 0.86
)
)
现在我的问题是,如果我尝试得到相同的结果,那么mysql查询将是什么呢?它将在内部执行forloop还是在查询本身中生成结果。
它还会在循环中执行单独的查询来检索子菜单列表吗?
1条答案
按热度按时间6l7fqoea1#
laravel的activerecord实现并没有将连接用于它的关系(对于其中的一些关系是这样的,但是对于像这样的关系是这样的)
belongsToMany
需要使用透视表/中间表的位置)。实际发生的情况是,eloquent将从表中获取相关的键,并执行另一个查询以获取所需的关系。
Post
有很多Comment
数据库里有3个有ID的帖子1
,2
以及3
.将导致:
查询1
查询2
它将遍历第二个查询的结果,并将它们与第一个查询加载的模型相匹配。
如果您想查看从您的laravel应用程序运行的查询,我建议您安装:
laravel调试栏
发条装置
除此之外,这些工具中的任何一个都将向您显示正在运行的查询。