如何在刀片视图中显示连接的表数据

时间:2016-04-22 11:07:27

标签: laravel eloquent blade

我有2张表有多对多的关系

Members:id,name,...

Locations:id,location_id

通过数据透视表连接

members_location:member_id,location_id

在我的位置模型中我有以下功能

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

LocationController.php将数据传递给刀片模板

    $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

返回错误。

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

如果我删除id属性:

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

我得到一个数组[{“id”:1,“first_name”:“Sa ..}]。如何从该数组中选择first_name属性

选择一个位置时修改输出

  
    
      
        

$位置 - &GT;成员         =&GT; Illuminate \ Database \ Eloquent \ Collection {#658              全部:[                App \ Member {#664                  id:1,

      
    
  

1 个答案:

答案 0 :(得分:1)

foreach($location->members as $member) ... 关系将返回一个集合而不是一个雄辩对象的单个实例。

要解决这个问题,你要么循环通过成员,例如

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

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

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

此外,仅仅是一个FYI,但由于多对多关系带来的n + 1问题,您最终会遇到大量数据库调用。为了克服这个问题,您可以在控制器中添加一个with方法,即

get

注意,如果您在链中有任何其他方法,则必须使用all而不是$name = $_GET['name'] ?? 'john doe'; (如上所述)。

希望这有帮助!

相关问题