首页 > 解决方案 > 如何将参数传递到链式 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;

如何将参数从附件模型传递给用户模型,或者有更好的方法来解决这个问题。

标签: phplaraveleloquenteloquent-relationship

解决方案


您需要明确地急切加载嵌套关系,如此处所述

$attachments = App\attachment::with('owner.profile')->get();

然后你应该能够像这样访问个人资料

$profile = $attachment->owner->profile;

推荐阅读