【问题标题】:Laravel - How to load a hasone relation on a hasmany relationLaravel - 如何在 hasmany 关系上加载 hasone 关系
【发布时间】:2020-01-18 13:04:42
【问题描述】:

我正在尝试在已加载的 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');

【问题讨论】:

    标签: laravel laravel-5 eloquent eloquent-relationship


    【解决方案1】:

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

    我能够通过简单地将关系加载到 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');
    }
    

    【讨论】:

      猜你喜欢
      • 2016-03-17
      • 1970-01-01
      • 2020-04-09
      • 1970-01-01
      • 1970-01-01
      • 2017-05-31
      • 2023-01-12
      • 2020-10-06
      • 1970-01-01
      相关资源
      最近更新 更多