尝试从子模型重新访问父模型的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',
'orders', 
'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中的eagerloaded模型。

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

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

最新更新