我对laravel关系感到非常惊讶,因为它与左联接相比可以提供没有重复条目的结果。 例如最近我尝试自连接对同一张表有很多
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还是在查询本身中产生结果。
它还会循环执行单独的查询以检索子菜单列表吗?
答案 0 :(得分:2)
Laravel的活动记录实现不使用联接来建立关系(它们中的某些关系也使用联接,但这适用于belongsToMany
之类的需要使用枢轴/中间表的关系)。
实际发生的是Eloquent将从表中获取相关键并执行另一个查询以获取所需的关系,例如
Post
有许多Comment
,并且数据库中有3个ID为1
,2
和3
的帖子。
Post::with('comments')->get();
将导致:
查询1
SELECT * from `posts`
查询2
SELECT * FROM `comments` WHERE `comment`.`post_id` in ('1', '2', '3')
它将检查第二个查询的结果,并将其与从第一个查询加载的模型进行匹配。
如果您想查看正在从Laravel应用程序中运行什么查询,那么我建议安装其中一个:
除其他外,这两个工具都可以向您显示正在运行的查询。