加载中...

关联预载入


版本 新增功能
5.0.4 一对一关联支持JOIN和IN两种方式预载入查询

关联查询的预查询载入功能,主要解决了N+1次查询的问题,例如下面的查询如果有3个记录,会执行4次查询:

  1. $list = User::all([1,2,3]);
  2. foreach($list as $user){
  3. // 获取用户关联的profile模型数据
  4. dump($user->profile);
  5. }

如果使用关联预查询功能,对于一对一关联来说,只有一次查询,对于一对多关联的话,就可以变成2次查询,有效提高性能。

  1. $list = User::with('profile')->select([1,2,3]);
  2. foreach($list as $user){
  3. // 获取用户关联的profile模型数据
  4. dump($user->profile);
  5. }

支持预载入多个关联,例如:

  1. $list = User::with('profile,book')->select([1,2,3]);

也可以支持嵌套预载入,例如:

  1. $list = User::with('profile.phone')->select([1,2,3]);
  2. foreach($list as $user){
  3. // 获取用户关联的phone模型
  4. dump($user->profile->phone);
  5. }

可以在模型的get和all方法中使用预载入,和使用select方法是等效的:

  1. $list = User::all([1,2,3],'profile,book');

如果要指定属性查询,可以使用:

  1. $list = User::field('id,name')->with(['profile'=>function($query){$query->withField('email,phone');}])->select([1,2,3]);
  2. foreach($list as $user){
  3. // 获取用户关联的profile模型数据
  4. dump($user->profile);
  5. }

关联预载入名称是关联方法名,从V5.0.4+版本开始,支持传入方法名的小写和下划线定义方式,例如如果关联方法名是userProfileuserBook的话:

  1. $list = User::with('userProfile,userBook')->select([1,2,3]);

等效于:

  1. $list = User::with('user_profile,user_book')->select([1,2,3]);

V5.0.4+版本开始一对一关联预载入支持两种方式:JOIN方式(默认)和IN方式,如果要使用IN方式关联预载入,在关联定义方法中添加

  1. namespace app\index\model;
  2. use think\Model;
  3. class User extends Model
  4. {
  5. public function profile()
  6. {
  7. // 设置预载入查询方式为IN方式
  8. return $this->hasOne('Profile')->setEagerlyType(1);
  9. }
  10. }

还没有评论.