雄辩的一对一关系的怪异行为

时间:2018-12-06 05:22:57

标签: laravel laravel-5.7

我需要获取具有相关个人资料的用户,但如果个人资料字段下方为空:

Route::get('/user', function (Request $request) {
  return $request->user()->load('profile'); // { id: 1, ... profile: null }
});

但是在这种情况下,配置文件字段已填写:

Route::get('/user', function (Request $request) {
    $user = $request->user();
    $profile = $user->profile;
    return $user; // { id: 1, ... profile: { name: 'alex', ... } }
});

您如何解释此行为以及在我的情况下加载Profile的正确方法是什么?

关系:

public function user(){
    return $this->belongsTo('App\Models\User');
}

public function profile(){   
    return $this->role == 'model' ? $this->hasOne('App\Models\Model\Profile') : $this->hasOne('App\Models\Client\Profile');
}

2 个答案:

答案 0 :(得分:1)

load()是懒惰的加载过程

使用load(),您首先需要运行初始查询,然后急于在以后加载该关系。这是“懒惰”的渴望加载。懒惰的渴望在已经获取父模型之后加载关系。

laravel with() method versus load() method

答案 1 :(得分:1)

仔细查看Eager loading

因此,要使用with()获取关系,它将同时运行两个查询,并将关系附加到模型集合,但是在使用load()时,首先要获取模型,然后在某些情况下使用load来获取关系数据。例如:

      $users = User::all();   //runs first query

      if($condition) {
      $users = $users->load('organisations');  //lets assume organisations is relation here.
       //here runs the 2nd query
       }

希望这会有所帮助。