首页 > 解决方案 > 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

标签: phplaravel

解决方案


您在 SQL 级别进行分组,但如果您希望将一个类别中的所有项目分组在一个集合中,则使用groupBy方法 from Collection。使用all() 方法获取所有项目的集合,然后使用groupBy()方法对itemsby进行分组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

希望它可以帮助你。:)


推荐阅读