为何使用with
关联查询的预查询载入功能,主要解决了N+1次查询的问题,例如下面的查询如果有3个记录,会执行4次查询:
举个栗子:
| | $list = User::all([1,2,3]); | | foreach($list as $user){ | | | | dump($user->profile); | | } |
|
如果使用关联预查询功能,对于一对一关联来说,只有一次查询,对于一对多关联的话,就可以变成2次查询,有效提高性能。
| | $list = User::with('profile')->select([1,2,3]); | | foreach($list as $user){ | | | | dump($user->profile); | | } |
|
单个预载入
| $list = User::with('profile')->select([1,2,3]); |
这里载入的profile 最后查询字段由你配置关联关系时候设置的filed来定,当然也可以在配置关联关系时不使用filed来指定,在with时指定的话,需要使用到闭包函数的方式指定
举个栗子:
| | $list = User::with('profile' => function($query){ | | $query->withField('id, name, status'); | | })->select([1,2,3]); |
|
多个关联模型预载入
在查询中经常会遇到需要预载入多个关联模型的情况,举个例子:
| $list = User::with(['profile', 'info', 'order'])->select([1,2,3]); |
多层关联关系载入
在预载入中,最复杂的属于多层预载入了,例如:user的order的product的brand
这个如果需要在user查询时预载入,写法如下:
| $list = User::with(['profile', 'info', 'order' => ['product' => ['brand]]])->select([1,2,3]); |
其实也简单,就是使用数组嵌套方式去嵌套就好了。
最复杂写法
就是在with 关联模型时,使用了闭包查询,而且还需要该模型下的其他关联模型,这种写法最复杂,直接上栗子:
| | $list = User::with('profile' => function($query){ | | $query->withField('id, name, status')->with('test'); | | })->select([1,2,3]); |
|
注意闭包里面的with,因为这个query 是整个profile 对象,所以闭包里面就跟单独查询profile 一样,该withField就 withField,该with 就with,还可以其他where 等操作。