我要组合数字列和单位列(单位列在单位表中)。这是我的代码:
@foreach ($item as $row)
<tr>
<td>{{ $row->amount }}</td>
<td>{{ $row->unit->unit }}</td>
</tr>
@endforeach
这是控制器
$reports = loan_reports::with('unit')
->get();
请,我该怎么办?
答案 0 :(得分:1)
为此,有几种解决方案,包括“使用联接”,“使用集合”,“使用API资源”和“定义访问器”。
要定义自定义访问器,请将getUnitAttribute
添加到您的loan_reports
模型中:
class loan_reportsextends Model
{
/**
* Get the report's unit.
*
* @return string
*/
public function getUnitAttribute()
{
return $this->relationLoaded('unit') ? $this->unit->unit : null;
}
}
然后您可以像这样使用它:
@foreach ($item as $row)
<tr>
<td>{{ $row->amount }}</td>
<td>{{ $row->unit }}</td>
</tr>
@endforeach
我已针对此答案解释了其他解决方案:https://stackoverflow.com/a/37489962/3477084