laravel - 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 以使其更简单。
解决方案
我只是想出了如何解决这个问题。
$user->comments->each->setRelation('user', $user);
将丢弃来自 $user 的 eagerloaded 模型。
但如果你手动设置关系each
。将包括所有急切加载的模型。
$user->comments->each(function($comment) use ($user) {
$comment->setRelation('user', $user);
});
推荐阅读
- python - 仅在某些位置运行基本 Python 应用程序时收到导入错误
- python - 是否可以在 python 中快速将一个非常大的 int 转换为字符串
- angular - 获取 BehaviorSubject 值并在组件中更新它会更新在另一个组件中读取的缓存数据
- angular - 如何在 Angular 中解析路由参数值?
- aws-lambda - AWS lambda 函数用于重启 ECS 集群服务之一
- node.js - 在 AWS lambda 上列出 cognito userpool 用户
- typescript - Webpack & typescript:观察导出的接口不起作用
- php - 网站开发:使用 LIKE 从数据库中查询时,sql 查询仅返回区分大小写的值
- python - Python-Ubuntu Raspberry 错误电报
- terraform - 想要关于 terraform List 类型变量的信息