php - laravel如何在item和category表的关系上显示一个category的item
问题描述
我之前问过这个问题,但没有得到任何答案,希望你有解决方案。因为我有 2 个表格、项目和类别,所以每个项目都有一个类别,一个类别可以有很多项目。我的问题是使用 groupby 函数时,但它为每个类别显示一个项目
商品型号:
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
解决方案
您在 SQL 级别进行分组,但如果您希望将一个类别中的所有项目分组在一个集合中,则使用groupBy
方法 from Collection
。使用all()
方法获取所有项目的集合,然后使用groupBy()
方法对items
by进行分组category_id
:
家庭控制器
类 HomeController 扩展控制器
{
public function getItems()
{
$items = Item::all()->groupBy('category_id');
return view('home',compact('items'));
}
}
在您的刀片文件中访问:
@foreach($items as $category_id => $categoryItems)
Category ID: {{ $category_id }} <br>
@foreach($categoryItems as $item)
<!-- Display Item Details Here -->
@endforeach
@endforeach
希望它可以帮助你。:)
推荐阅读
- python - 根据另一个相同形状的 ndarray 的条件更改 ndarray 的值
- javascript - 如何在页面加载时选择第二个引导选项卡?
- vue.js - laravel-mix 升级后应用不再看到全局变量
- sharepoint-2013 - SharePoint 2013:使用 StratusForms 我删除了“NewForm.aspx”,现在只有新的“NewForm”不起作用
- monitoring - 高标签基数但低度量/标签计数和不频繁采样是 Prometheus 可接受的用例吗?
- c# - 寻找一种使用 Entity Framework Core 为每一行检索一组多对多子项的有效方法
- sql-server - 用于全文搜索的自定义过滤器。IFilter 实现
- javascript - 对数组键值对象的数组进行排序
- telegram-bot - 电报机器人 Python
- android - 使用 Kotlin 在 Recycler View 中显示 JSON 值