如何在Laravel中将来自不同表的2列合并为1表中的1列

时间:2019-12-24 09:34:35

标签: php laravel

我要组合数字列和单位列(单位列在单位表中)。这是我的代码:

@foreach ($item as $row)
<tr>
    <td>{{ $row->amount }}</td>
    <td>{{ $row->unit->unit }}</td>
</tr>
@endforeach

这是控制器

$reports = loan_reports::with('unit')
            ->get();

请,我该怎么办?

1 个答案:

答案 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