如何在 blade 视图中显示连接的 table 数据

How to display connected table data in blade view

我有 2 个 table 具有多对多关系

Members: id, name , ...

Locations: id,location_id

由枢轴连接 table

members_location: member_id, location_id

在我的 Location 模型中,我有以下功能

public function members(){
        return $this->belongsToMany('App\Member','location_member','location_id','member_id');
    }

LocationController.php 将数据传递到 blade 模板

    $locations = Location::All();
    return view('locations.overview',['locations' => $locations]);

所以在我的 overview.blade.php 中,我执行以下操作

            @include('includes.message-block')
        <!-- get a list of locations -->
                <table class="member_overview table table-striped table-hover">
        <thead>
            <tr>
                <th>Naam</th>
                <th>Locatie</th>
                <th>Opmerking</th>
            </tr>
        </thead>
        <tbody>
        @foreach($locations as $location)
            <tr>
                <td>
                    {{$location->location_id}}
                </td>
                <td>
                    {{$location->members->id}}                      
                </td>
                <td>

                </td>
            </tr>
        @endforeach

其中returns一个错误。

未定义属性:Illuminate\Database\Eloquent\Collection::$id(视图:...)

如果我删除 id 属性 于:

<td>
                        {{$location->members->id}}                      
                    </td>

我得到一个数组 [{"id":1,"first_name":"Sa ..}]。我怎么能 select first_name 属性 来自那个数组

当 selecting 一个位置

时修补器输出

$location->members => Illuminate\Database\Eloquent\Collection {#658 all: [ App\Member {#664 id: 1,

belongsToMany 关系将 return 收集的不是 eloquent 对象的单个实例。

要解决此问题,您将循环遍历成员,例如

foreach($location->members as $member) ...

of 如果你只想要第一个那么你可以这样做:

$location->members->first()->id

此外,仅供参考,但由于多对多关系带来的 n+1 问题,您最终可能会进行大量数据库调用。为了克服这个问题,您可以在控制器中简单地添加一个 with 方法,即

$locations = Location::with('members')->get();

注意,如果链中有任何其他方法,则必须使用 get 而不是 all(如上)。

希望对您有所帮助!