首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Laravel - groupBy有一个类别的项目?

Laravel - groupBy有一个类别的项目?
EN

Stack Overflow用户
提问于 2018-06-26 05:54:59
回答 2查看 0关注 0票数 0

我有两个表格,项目和类别,每个项目有一个类别,一个类别有很多项目。所有的工作都适合我,但它只显示每个类别的id一个项目我如何显示每个类别的所有项目

项目型号:

代码语言:javascript
复制
 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');
}
}

类别模型

代码语言:javascript
复制
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');
  }
  }

调节器

代码语言:javascript
复制
class HomeController extends Controller
{
public function getItems()
{
$items = Item::groupBy('category_id')->get();   
return view('home',compact('items'));
}
}

HTML

代码语言:javascript
复制
 @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
EN

回答 2

Stack Overflow用户

发布于 2018-06-26 14:50:21

代码语言:javascript
复制
$categories::with('items')->get()

这将给你所有的类别与他们的项目,假设反比关系是由定义 items()

然后你可以通过使用来访问该项目和类别。由于你通过类别获得项目,它们将被“分组”。

代码语言:javascript
复制
@foreach($categories as $category)
    @foreach($category->items as $item)

    @endforeach
@endforeach
票数 0
EN

Stack Overflow用户

发布于 2018-06-26 15:03:20

这就是解决办法

代码语言:txt
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100005524

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档