2016-10-31 21 views
1

我有兩個表,類別和產品。每個類別都有id和name。每個產品都有ID,名稱和類別ID。現在我想在用戶點擊特定category_id.so相關產品時顯示在每個類別選項卡上,以在每個選項卡上加載數據。我嘗試過,但無法獲得解決方案。Laravel:如何在選項卡上顯示因變量

分類型號:

class Category extends Model 
{ 
    public function products() 

    { 
     return $this->hasMany('App\Product'); 
    } 
} 

產品型號:

class Product extends Model 
{ 
    public function category() 
     { 
      return $this->belongsTo('App\Category'); 
     } 

} 

這裏是我的控制器:

public function gettestItem() { 
       $categories = Category::with('products')->get(); 
       return view('products', compact('categories')); 
      } 

這裏是視圖:

<div class="container"> 
     <div id="content">    
      <ul id="tabs" class="nav nav-tabs" data-tabs="tabs"> 
      @foreach ($categories as $category)    
       <li><a href="#{{$category->id}}" data-toggle="tab" >{{$category->name}}</a></li> 
      @endforeach 
      </ul> 

      <div id="my-tab-content" class="tab-content"> 
       @foreach($categories as $category) 
        @foreach($category->products as $product) 
        <div class="tab-pane " id="{{$category->id}}"> 
         {{$product->name}} 
        </div> 
        @endforeach 
       @endforeach 
      </div>  
     </div> 
    </div> 

這裏是路線:

Route::get('/testItem',[ 
'uses'=>'[email protected]', 
'as'=>'testItem' 
]); 

如果有人可以幫助我解決這個問題可以理解的。

+1

你可能要考慮在讀了[關係]( https://laravel.com/docs/5.2/eloquent-relationships)以及如何使用laravel [查詢生成器](https://laravel.com/docs/5.2/queries) –

回答

1

如果你定義了你的架構和關係正確,然後函數應爲:

public function gettestItem() { 
    $categories = Category::with('products')->get(); 
    return view('products', compact('categories')); 
} 

那麼你就可以訪問每個類別的產品:

foreach ($categories as $category) { 
    $category->product; // gives all products corresponding to $category 
} 

還請閱讀Docs

更新

你的第二foreach應爲:

<div id="my-tab-content" class="tab-content"> 
    @foreach($categories as $category) 
    <div class="tab-pane" id="{{$category->id}}"> 
     @foreach($category->products as $product) 
     <div> 
      {{$product->name}} 
     </div> 
     @endforeach 
    </div> 
    @endforeach 
</div> 

您還可以使用下面的代碼獲取只有那些categories已相應products

$categories = Category::has('products')->with('products')->get(); 
+0

我已經改變了雄辯的解決方案。但無法獲得解決方案。您能否看到更新問題? – Hola

+0

你有什麼具體的錯誤嗎?而且你也可以展示你的期望和你得到的東西。 –

+0

問題出現在類別ID中,只有一種產品顯示,而不是顯示多種產品。 – Hola

相關問題