在刀片模板laravel中显示相关的表信息

时间:2016-04-25 07:28:52

标签: php laravel-5 blade

我的表之间有以下关系

relation

在我的模型中,我有以下代码:

位置模型:

public function member() {
  return $this->belongsTo('App\Member','member_id');
 }

会员模特:

public function locations(){
    return $this->hasMany('App\Location','member_id');
}

现在在我的位置控制器中,我创建了以下功能。

public function getFinalData(){
    $locations = Location::with('member')->whereNotNull('member_id')->get();
    return view('locations.final-list',['locations'=>$locations]);
}

但是,在我的刀片模板中,我无法遍历成员属性

<ul>
    @foreach($locations as $location)
      <li>{{$location->id}}</li>
        <li>
         @foreach($location->member as $member)
          {{$member->id}}
         @endforeach
        </li>
    @endforeach
</ul>

这给了我以下错误:      尝试获取非对象的属性(查看:locations / final-list.blade.php)

更新:我想要实现的结果对应于此查询

SELECT locations.location_id,locations.name,members.first_name,          members.last_name , locations.meters
FROM locations,members
WHERE locations.member_id = members.id

更新2:

所以我试图访问一个单独的位置,并附加一个,并且完美无缺

public function getFinalData(){
    //$locations = Location::with('member')->whereNotNull('member_id')->get();
    $location = Location::find(0);

    return view('locations.final-list',['location'=>$location]);
}

在最终名单中 $位置 - &GT;成员 - &GT; first_name的

**更新3 ** 一条记录的修补程序输出: enter image description here

2 个答案:

答案 0 :(得分:0)

In your Location model, rewrite below function:-

public function member()
{
    return $this->belongsTo('App\Member', 'id');
}

Get all locations with member detail as below:-

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

Hope it will work for you :-)

答案 1 :(得分:0)

在blade中显示相关表信息如下图:

模型关系 位置模型:

public function member() {
   return $this->belongsTo('App\Member','member_id');
}

会员型号:

public function locations(){
    return $this->hasMany('App\Location','member_id');
}

获取控制器中的所有位置

$locations = Location::all();
return view('locations.final-list', compact('locations'));

$locations = Location::orderBy('id')->get();
return view('locations.final-list', compact('locations'));

在您的视图(刀片)中编写以下代码:

<div>
    @if($locations)
        @foreach($locations AS $location)
            <div>{{ $location->id }}</div>
            @if($location->member)
                @foreach($location->member AS $member)
                    <div>
                        {{ $member->id }}
                    </div>
                @endforeach
            @endif
        @endforeach
    @endif
</div>