Laravel 5.2-具有一通或自定义属性
以下是我的模型:Laravel 5.2-具有一通或自定义属性,laravel,eloquent,Laravel,Eloquent,以下是我的模型: 员工小时数属于报告 报告属于雇主 在很多地方,我们都在做$employerHour->report->employer,将雇主与employerHour联系起来。(请记住,我没有能力更改模式)。我决定在employeehour模型上执行以下操作: /** * Attribute for retrieving the Employer directly from employer hours * @return App\Models\Employer */ public
属于员工小时数
报告
属于报告
雇主
$employerHour->report->employer
,将雇主与employerHour
联系起来。(请记住,我没有能力更改模式)。我决定在employeehour
模型上执行以下操作:
/**
* Attribute for retrieving the Employer directly from employer hours
* @return App\Models\Employer
*/
public function getEmployerAttribute()
{
return $this->report->employer;
}
这几乎像是一个黑客。然而,这种情况在很多情况下都会发生,并且变得非常有用。我在想,一定有一种关系,但似乎不是这样。这是正确的方法还是我遗漏了什么?总有一种方法:)
可以通过连接表来实现这一点。例如:
// EmployerHour.php
public function employer()
{
return Employer
::select('employers.*')
->join('reports', 'employers.id', '=', 'reports.employer_id')
->join('employerhours', 'reports.id', '=', 'employerhours.report_id')
->where('employerhours.id', $this->id);
}
也许您需要更改此示例中使用的列名