0

我使用 laraver 生成器(infyom)。在“公司”表中有合作伙伴ID,但没有合作伙伴的名称。我想要显示另一个名为partners的表中的合作伙伴名称。我怎样才能做到这一点?

公司(table.blade.php)

<div class="table-responsive">
    <table class="table" id="companies-table">
        <thead>
            <tr>
                <th>Name</th>
                <th>Partner ID</th>
                <th>Type</th>
                <th>Nip</th>
                <th>Street</th>
                <th>Building Num</th>
                <th>Apartment Num</th>
                <th>Postal Code</th>
                <th>Place</th>
                <th>Floor</th>
                <th colspan="3">Action</th>
            </tr>
        </thead>
        <tbody>
        @foreach($companies as $company)
            <tr>
                <td>{{ $company->name }}</td>
                <td>{{ $company->partner_id }}</td>
                <td>{{ $company->type }}</td>
                <td>{{ $company->NIP }}</td>
                <td>{{ $company->street }}</td>
                <td>{{ $company->building_num }}</td>
                <td>{{ $company->apartment_num }}</td>
                <td>{{ $company->postal_code }}</td>
                <td>{{ $company->place }}</td>
                <td>{{ $company->floor }}</td>
                <td>
                    {!! Form::open(['route' => ['companies.destroy', $company->id], 'method' => 'delete']) !!}
                    <div class='btn-group'>
                        <a href="{{ route('companies.show', [$company->id]) }}" class='btn btn-default btn-xs'><i class="glyphicon glyphicon-eye-open"></i></a>
                        <a href="{{ route('companies.edit', [$company->id]) }}" class='btn btn-default btn-xs'><i class="glyphicon glyphicon-edit"></i></a>
                        {!! Form::button('<i class="glyphicon glyphicon-trash"></i>', ['type' => 'submit', 'class' => 'btn btn-danger btn-xs', 'onclick' => "return confirm('Are you sure?')"]) !!}
                    </div>
                    {!! Form::close() !!}
                </td>
            </tr>
        @endforeach
        </tbody>
    </table>
</div>

4

2 回答 2

0

您可以使用 Eloquent 提供的关系功能,通过 Company 上的此partner_id字段将 Company 模型与 Partner 模型相关联:

class Company ...
{
    public function partner()
    {
        return $this->belongsTo(Partner::class);
    }
}

在您的控制器中,您可以立即加载传递给视图的所有公司模型的关系

public function index()
{
    return view('companies.index', [
        'companies' => Company::with('partner')->paginate(...),
    ]);
}

在视图中,您可以访问每个公司的合作伙伴:

@foreach ($companies as $company)
    ...
    {{ $company->partner->name ?? 'none'}}
    ...
@endforeach

Laravel 7.x 文档 - Eloquent - 关系 - 一对多(反向) belongsTo

Laravel 7.x 文档 - Eloquent - 关系 - 急切加载 with

Laravel 7.x 文档 - Eloquent - 关系 - 动态属性

于 2020-05-25T14:48:57.430 回答
0

将此功能添加到您的公司模型中

public function partners(){
     return $this->hasMany(Partner::class, 'partner_id', 'id');
}

/*
using in your foreach => $company->partners->name

Don't forget to import Partner model to your Companies model
*/
于 2020-05-25T14:12:50.317 回答