php - 如何将参数传递到链式 Laravel Eloquent 关系中的位置
问题描述
在向关系添加 where 子句时,我在 Laravel 中链接多个关系时遇到问题:
用户模型:与 UserProfiles 的一对多关系
列:id、用户名、电子邮件、current_region
class User
{
public function profile()
{
return $this->hasOne(Profile::class)->where('region_code',$this->current_region);
}
}
注意: 在这种情况下,我使用 hasOne 来获取单个记录,而关系是 oneToMany
用户档案模型:
列:名称、编号、user_id、region_code
附件型号:
列:文件、名称、user_id、region_code
class Attachment
{
public function owner()
{
return $this->belongsTo('App\User', 'user_id');
}
}
我需要从附件模型访问 userProfle。
attachment->user->userprofile; // returns null because $this->current_region is not accessible as the context for user model is not available yet
但是我可以直接从 User 模型访问 userProfile
$user->userProfile // return expected response;
如何将参数从附件模型传递给用户模型,或者有更好的方法来解决这个问题。
解决方案
您需要明确地急切加载嵌套关系,如此处所述
$attachments = App\attachment::with('owner.profile')->get();
然后你应该能够像这样访问个人资料
$profile = $attachment->owner->profile;
推荐阅读
- vue.js - Vuelidate:与 $each 结合的动态验证
- database - 如何在无服务器环境中“本地”缓存一批 ID?
- php - laravel 8.4 中的错误?未保存在事务中的 belongsToMany 关系对象
- spring-boot - 使用 oauth2.0 的 EWS 现代身份验证:远程服务器返回错误:(401)未授权
- javascript - Headers 类的模块/Javascript/
- string - 如何在powershell中替换此字符串中的变量?
- php - 构建具有多级元素的递归数组
- vb.net - 在 Ms Chart Control VB.Net 中显示两项数据
- reactjs - TypeScript 错误:更新 React 对象中的元素获取未定义的错误 ID
- react-native - 如何更改博览会通知图标并添加自定义声音