【问题标题】:Weird behaviour of Eloquent One To One relationship雄辩的一对一关系的奇怪行为
【发布时间】:2019-05-07 18:41:45
【问题描述】:

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

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', ... } }
});

您如何解释这种行为以及在我的情况下加载配置文件的正确方法是什么?

关系:

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');
}

【问题讨论】:

  • 查看这篇文章了解预加载:laravel-news.com/eloquent-eager-loading
  • return $request->user()->with('profile') 返回错误“Illuminate\Database\Eloquent\Builder 类的对象无法转换为字符串”

标签: laravel laravel-5.7


【解决方案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
       }

希望这会有所帮助。

【讨论】:

  • return $request->user()->with('profile') 返回错误“Illuminate\Database\Eloquent\Builder 类的对象无法转换为字符串”
  • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
  • @Cœur 我实际上是 stackoverflow 的新手,对这些小事一无所知,谢谢指出,以后会记住的。
  • @kshitij 如果您打开我之前评论的“来自评论”链接,您可能会看到您的答案很快就会被删除,除非您快速改进它。
【解决方案2】:

load() 是延迟加载

使用 load(),您需要先运行初始查询,然后在稍后的某个时间点急切加载关系。这是“懒惰”的急切加载。在已经检索到父模型后,延迟加载关系。

laravel with() method versus load() method

【讨论】:

  • return $request->user()->with('profile') 返回错误“Illuminate\Database\Eloquent\Builder 类的对象无法转换为字符串”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-27
  • 2012-10-08
  • 2020-09-20
  • 2018-11-14
  • 2015-07-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多