2017-05-29 55 views
0

請我希望基於其category id獲取作物,會很高興,如果這能不使用JavaScript提取記錄基地 - Laravel

顯示頁面

<div class="cat-list"> 
    <h3 class="cat-title"> 
     <a href="/filterByCategory/{{$category->cat_id}}"> 
      <i class="fa fa-car ln-shadow"></i> 
      {{$category->cat_name}}<span class="count">{{$category->count()}}</span> 
     </a> 
     <span data-target=".cat-id-1" data-toggle="collapse" class="btn-cat-collapsed collapsed"> 
      <span class=" icon-down-open-big"></span> 
     </span> 
    </h3> 
    <ul class="cat-collapse collapse in cat-id-1"> 
    @php 
     $catID = $category->cat_id; 
     //want to fetch crops base on the $catID and display in foreach 
    @endphp 
    </ul> 
</div> 

控制器功能實現

public function index() 
{ 
    $categories = Category::all(); 

    $crops = Crop::all(); 

    return view('public.index' , compact('categories' , 'crops')); 
} 

作物型號

public function category() 
{ 
    return $this->belongsTo(Category::class, 'cat_id', 'crop_cat') 
} 

分類模式

public function category() 
{ 
    return $this->hasmany(Category::class, 'crop_cat','cat_id') 
} 
+0

您尚未概述作物與類別的關係。發佈數據庫模式和/或模型關係。 – fubar

回答

0

您可用此法您的類別添加到模型:

public function crops() { 
    return $this->hasMany(Crop::class, 'catID'); 
} 

這個功能您的作物模型:

public function category() { 
    return $this->belongsTo(Category::class, 'catID'); 
} 

之後,您可以基本遍歷刀片模板上的所有類別,並在此循環中回顯當前類別的所有作物。然後,這可能是這樣的:

@foreach ($categories as $category) 
    {{ $category->name }} 

    @foreach ($category->crops as $crop) 
     {{ $crop->title }} 
    @endforeach 
@endforeach 

您可以找到有關Laravel here雄辯關係的更多信息。