首页 > 解决方案 > Laravel - 如何在 hasmany 关系上加载 hasone 关系

问题描述

我正在尝试在加载的 hasmany 关系上加载 hasone 关系。

基本上,我已经加载了我的完成日志,但还想为每个加载的完成日志记录加载 pool_section 模型关系。

$appointments = Appointment::primaryAppointments()->ofReportingPeriod($reportingPeriod->id)->take(5)->get();

$appointments = $appointments->load('profile', 'department')->load(['completion_logs' => function ($query) use ($reportingPeriod) {
    $query->where('reporting_period_id', $reportingPeriod->id)->whereNotNull('pool_section_id')->orderBy('pool_section_id');
}]);

尝试将 pool_section 关系从上面加载到加载的完成日志中:

class PoolSectionCompletion extends Model

public function pool_section()
{
     return $this->belongsTo('App\Models\PoolSection', 'pool_section_id', 'id');
}

class Appointment extends Model

public function completion_logs()
{
     return $this->hasManyThrough('App\Models\PoolSectionCompletion', 'App\Models\Profile', 'id', 'profile_id', 'profile_id', 'id');
}

我正在尝试加载选择完成日志,然后根据 id 加载 pool_section 关系,以便为每个加载的完成日志获取 pool_section 数据。任何帮助表示赞赏。

在此处输入图像描述

似乎如果我添加如下关系 - 它正在正确映射,但会为每个报告期带来所有完成日志,而不仅仅是每个路线定义的日志。我需要定义报告期间的完成日志,但映射到 pool_section 的 hasone 关系。

$appointments = $appointments->load('profile', 'department')->load(['completion_logs' => function ($query) use ($reportingPeriod) {
    $query->where('reporting_period_id', $reportingPeriod->id)->whereNotNull('pool_section_id')->orderBy('pool_section_id');
}])->load('completion_logs.pool_section');

标签: laravellaravel-5eloquenteloquent-relationship

解决方案


它永远不会失败......花费数天/数小时尝试解决,然后最终发布问题,只是为了能够在几个小时后通过一些额外的努力解决它。

我能够通过简单地将关系加载到 hasmany 关系来实现我所需要的。

class Appointment extends Model

public function completion_logs()
{
     return $this->hasManyThrough('App\Models\PoolSectionCompletion', 'App\Models\Profile', 'id', 'profile_id', 'profile_id', 'id')->with('pool_section');
}

推荐阅读