laravel多级关系的问题,急于加载,试图从子模型中重新访问父模型

问题描述

我想问一下什么是最好的实施方式。

$users = User::with(['group','orders','comments'])->get()

$users->each(function($user) {
    $user->comments->each(function($comment) {
        // I kNow I can just add 'use' in the closure function to access the user again
        // but let's just say that the user variable is not accessible at this point of the code.
        // and the only way to access the user again is via $comment variable
        // when I access user here. it tries to fetch in the database
        $user = $comment->user;
    });
});

我的第一个解决方案是添加以下代码行。

$user->comments->setRelation('user',$user);

这将解决此问题,因为用户将不再获取数据库。 但是出现另一个问题。设置关系后,其他预先加载的用户关系将不包含在此级别中 例如$user->group$user->orders

这是我的第二种解决方法

$users = User::with([
'group','comments',// trying to eager load the comments user again
'comments.user','comments.user.group','comments.user.orders'])->get()

这可以工作,但我认为这不是最好的解决方案。特别是当我有很多渴望的嵌套关系时。 在示例中,我只将其限制为3。

解决方法

我只是想出了解决问题的方法。

$user->comments->each->setRelation('user',$user);将从$ user丢弃预先加载的模型。

但是如果您通过each手动设置关系。所有急切加载的模型都将包括在内。

$user->comments->each(function($comment) use ($user) {
     $comment->setRelation('user',$user);
});