我有兩個表,類別和產品。每個類別都有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'
]);
如果有人可以幫助我解決這個問題可以理解的。
你可能要考慮在讀了[關係]( https://laravel.com/docs/5.2/eloquent-relationships)以及如何使用laravel [查詢生成器](https://laravel.com/docs/5.2/queries) –