我有两个表格,项目和类别,每个项目有一个类别,一个类别有很多项目。所有的工作都适合我,但它只显示每个类别的id一个项目我如何显示每个类别的所有项目
项目型号:
class Item extends Model
{
protected $table="items";
protected $fillable=
['item_title','category_id','item_price','item_details','item_image'];
protected $primaryKey='item_id';
public $timestamps=false;
public function categories()
{
$this->hasOne('App\category','category_id','category_id');
}
}
类别模型
class Category extends Model
{
protected $table="categories";
protected $fillable=['category_name'];
protected $primaryKey='category_id';
public $timestamps=false;
public function items()
{
$this->hasMany('App\items','category_id','category_id');
}
}
调节器
class HomeController extends Controller
{
public function getItems()
{
$items = Item::groupBy('category_id')->get();
return view('home',compact('items'));
}
}
HTML
@foreach($items as $indexKey => $item)
<div class="MenuPage_contentArea">
<div class="Category_root" id="one">
<div class="Category_categoryHeader">
<div><h2 class="Category_name">{{$item->item_category}}</h2></div>
<div class="Category_description"></div>
</div>
<div class="Category_itemsContainer">
<div class="Category_itemContainer">
<button class="Item_root Button_root">
<div class="Item_image" style="background-image: url('{{ asset('images/' . $item->item_image) }}');"></div>
<div class="Item_itemContent">
<div class="Item_topSection">
<span class="Item_name">{{$item->item_title}}</span>
<span class="Item_price">${{$item->item_price}}</span></div>
<div class="Item_description">{{$item->item_details}}</div>
</div>
</button>
</div>
</div>
</div>
</div>
@endforeach
发布于 2018-06-26 14:50:21
$categories::with('items')->get()
这将给你所有的类别与他们的项目,假设反比关系是由定义 items()
然后你可以通过使用来访问该项目和类别。由于你通过类别获得项目,它们将被“分组”。
@foreach($categories as $category)
@foreach($category->items as $item)
@endforeach
@endforeach
发布于 2018-06-26 15:03:20
这就是解决办法
public function getItems()
{
$items = Item::all()->groupBy('category_id');
return view('home',compact('items'));
}
@foreach($items as $category_id => $categoryItems)
{{ $category_id }}
@foreach($categoryItems as $item)
<!-- Item Details-->
@endforeach
@endforeach
https://stackoverflow.com/questions/-100005524
复制相似问题