首页 > 解决方案 > 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);

这将解决问题,因为用户将不再在数据库中获取。但另一个问题出现了。设置好关系后,其他eagerloaded的用户关系就不会包含在这个层级了,如$user->group、 、$user->orders

这是我的第二个解决方案

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

这会起作用,但我认为这不是最好的解决方案。特别是当我有很多我渴望加载的嵌套关系时。我只是在示例中将其限制为 3 以使其更简单。

标签: laravellaravel-5eloquenteager-loadingeloquent-relationship

解决方案


我只是想出了如何解决这个问题。

$user->comments->each->setRelation('user', $user);将丢弃来自 $user 的 eagerloaded 模型。

但如果你手动设置关系each。将包括所有急切加载的模型。

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

推荐阅读