【发布时间】:2016-08-15 23:42:06
【问题描述】:
我有 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 (View: ...)
如果我将 id 属性放在:
<td>
{{$location->members->id}}
</td>
我得到一个数组 [{"id":1,"first_name":"Sa ..}]。如何从该数组中选择 first_name 属性
选择一个位置时的修补输出
$location->成员 => Illuminate\Database\Eloquent\Collection {#658 全部: [ 应用\会员{#664 编号:1,
【问题讨论】:
-
是位置和成员之间会有多对多的关系吗?
-
@AlankarMore 是的,他们可以
-
我想你提到了错误的表名是错字吗?问题描述和查询/关系代码中的“members_location”是否已将其称为“location_member”?这个“location_member”是什么?
-
@AlankarMore 位置成员是连接位置和成员表的数据透视表