簡體   English   中英

在blade模板laravel中顯示相關表格信息

[英]Showing related table information in blade template laravel

我的表之間有以下關系

關系

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

位置模型:

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>

這給了我以下錯誤:試圖獲取非對象的屬性(視圖:位置/最終列表.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]);
}

在最終列表 $location->member->first_name

**更新 3 ** 一條記錄的 Tinker 輸出: 在此處輸入圖片說明

在您的位置模型中,重寫以下函數:-

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

獲取所有位置的成員詳細信息如下:-

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

希望它對你有用:-)

在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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM