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

Laravel循环中如何过滤重复数据仅显示唯一条目

解决Laravel循环中重复数据显示问题

问题根源

外层循环的$list中存在多个关联到同一个Collection的条目,导致内层循环每次匹配到对应ID就输出一次,最终出现重复数据。另外你在Blade里写的@foreach ($list as $list)会覆盖原变量,这也是需要修正的细节。

解决方案

方法一:控制器层面获取唯一集合(推荐)

直接从$list中提取所有不重复的Collection ID,再用这些ID查询对应的Collection数据,避免视图层做冗余循环:

public function product_list($id){
    $list = ProductList::where('CategoryId',$id)
        ->where('Status',true)
        ->with('item')
        ->get();

    // 提取所有唯一的Collection ID并过滤空值
    $collectionIds = $list->pluck('item.Collection')->unique()->filter();

    // 根据唯一ID查询不重复的Collection数据
    $collection = Collection::whereIn('Id', $collectionIds)
        ->where('Status', true)
        ->get();

    return view('frontend/products/product-list',compact('menu','submenu','list','collection'));
}

对应的Blade代码简化为直接循环去重后的集合:

@foreach ($collection as $col)
    {{ $col }}<br>
@endforeach

方法二:视图层控制重复输出

如果需要保留原有循环逻辑,可以在视图中维护一个数组记录已输出的Collection ID,避免重复渲染:

@php
    $shownIds = [];
@endphp
@foreach ($list as $item)
    @foreach ($collection->where('Id', $item->item->Collection) as $col)
        @if (!in_array($col->Id, $shownIds))
            {{ $col }}<br>
            @php $shownIds[] = $col->Id; @endphp
        @endif
    @endforeach
@endforeach

方法三:调整模型关联简化查询

如果ProductList通过item关联到Collection,可以在模型中定义hasOneThrough关联:

// ProductList模型中
public function collection()
{
    return $this->hasOneThrough(
        Collection::class,
        Item::class,
        'id',          // Item表关联字段
        'Id',          // Collection表关联字段
        'item_id',     // ProductList表关联Item的字段
        'Collection'   // Item表关联Collection的字段
    );
}

然后控制器直接查询并去重:

$collection = ProductList::where('CategoryId',$id)
    ->where('Status',true)
    ->with('collection')
    ->get()
    ->pluck('collection')
    ->filter() // 过滤空关联
    ->unique('Id');

关于你之前groupBy失败的原因

你之前的groupBy只选择了Id和统计数,没有获取完整的Collection字段。如果要用groupBy,需要确保选中的所有字段都包含在groupBy中(MySQL严格模式下要求),或者改用distinct()更简单:

// 正确的groupBy写法(需关闭MySQL严格模式或groupBy所有字段)
$collection = Collection::where('Status',true)
    ->whereIn('Id', $collectionIds)
    ->select('Id', 'Code', 'Name', 'Status')
    ->groupBy('Id', 'Code', 'Name', 'Status')
    ->get();

// 更简洁的distinct写法
$collection = Collection::where('Status',true)
    ->whereIn('Id', $collectionIds)
    ->distinct()
    ->get();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 09:54:19