laravel - 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');
解决方案
它永远不会失败......花费数天/数小时尝试解决,然后最终发布问题,只是为了能够在几个小时后通过一些额外的努力解决它。
我能够通过简单地将关系加载到 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');
}
推荐阅读
- j - 如何在J中将数据数组从宽到长重塑?
- git - VSCode - 选项卡图标颜色反映 git 状态
- r - 如何将变量用于块选项?
- android - lateinit 属性 editTextName 尚未初始化
- python-3.x - Python Selenium 获取 xpath 的第 n 个元素
- python - 仅使用递归和 python 龟制作谢尔宾斯基地毯时遇到问题
- php - 使用多维数组从mysql获取结果
- mysql - 如何使用容器化的 mysql 服务设置本地 laravel
- python - 如何解决google ads api(python)中的customer_id错误
- python - 在输入时输入python,在更改输入时重新运行代码