You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel如何实现商品归入对应分类展示,看不懂现有SQL逻辑怎么办

问题根因

  1. 你现有控制器查询中使用了groupBy('categories.category_name'),会将同分类的所有商品合并为1条记录,最终每个分类只会返回1条商品数据,无法展示分类下的全部商品。
  2. 视图层没有嵌套遍历分类下的商品列表,只能输出单条商品。
  3. 原控制器return语句存在语法错误,传参数组缺少左侧方括号。

目标效果示意图


修正代码

控制器代码

// 先查询所有关联了分类的商品
$items = DB::table('items')
    ->join('categories', 'items.category_id', 'categories.id')
    ->select('items.item_name', 'items.item_price', 'categories.category_name', 'categories.description')
    ->get();
// 按分类名将商品分组,得到「分类名称 => 对应商品列表」的结构
$categories = $items->groupBy('category_name');

return view('welcome', ['categories' => $categories]);

视图(welcome.blade.php)代码

@extends('layouts/layout')
@section('content')
<div class="container-fluid">
    @foreach ($categories as $categoryName => $goodsList)
        {{-- 输出分类标题 --}}
        <h4>{{$categoryName}}</h4>
        <div class="row">
            {{-- 嵌套遍历当前分类下的所有商品 --}}
            @foreach($goodsList as $goods)
                <div class="col-sm-4">
                    <h6>{{$goods->item_name}}</h6>
                    <span>价格:{{$goods->item_price}}</span>
                </div>
            @endforeach
        </div>
    @endforeach
</div>
@endsection

可选优化(Laravel最佳实践)

如果使用模型关联实现,代码会更简洁易维护:

  1. 给分类模型新增商品关联方法
// app/Models/Category.php
public function items()
{
    return $this->hasMany(Item::class, 'category_id', 'id');
}
  1. 控制器查询简化为
$categories = Category::query()->with('items')->get();
return view('welcome', compact('categories'));
  1. 对应视图调整遍历逻辑即可
@foreach ($categories as $category)
    <h4>{{$category->category_name}}</h4>
    <div class="row">
        @foreach($category->items as $item)
            <div class="col-sm-4">
                <h6>{{$item->item_name}}</h6>
            </div>
        @endforeach
    </div>
@endforeach

内容的提问来源于stack exchange,提问作者Amir Adamov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 12:09:00